0
私はLinuxコマンド "ls -l | tail -n 2"をCコードの単純なパイプで実行しようとしています。linux terminalコマンドとCコードのパイプ
あなたのヒントを追加しましたが、これはうまくいきましたが、出力が正確にはそうではありません。出力を2行ではなく1行に出力し、ユーザー入力を閉じるのを待ちます。 は、ここに新しいコードです:
#include "stdio.h"
#include "unistd.h"
#include "stdlib.h"
#include "sys/wait.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main()
{
char line[100];
pid_t pid;
int fd[2];
int status;
char* ls_arguments[] = {"ls", "-l", NULL};
char* tail_arguments[] = {"tail", "-n", "2", NULL};
pipe(fd);
pid = fork();
if(pid == 0)//ls client
{
close(1);
dup(fd[1]);
close(fd[0]);
execvp("ls", ls_arguments);
}
pid = fork();
if(pid == 0)//tail client
{
close(0);
close(fd[1]);
dup(fd[0]);
execvp("tail", tail_arguments);
}
wait(pid, 0, WNOHANG);
close(fd[0]);
close(fd[1]);
}
このパイプ入力としてそれを取得し、実行します次の「尾」クライアントへの「ls -l」コマンドと出力を実行すべきである「テール-n 2」コマンドを実行して最終出力を出力しますが、端末は何も出力しません。どんな助け?すべての
は、execvpの 'の後にコードを置くことにはポイント()'はありません。 – Barmar
それぞれが 'exec'を呼び出す前に、' ls'クライアントで 'close(fd [0])'を、 'tail'クライアントで' close(fd [1]) 'を実行する必要があります。 – Barmar
親プロセスは両方を閉じる必要があります。 – Barmar