を使用したくない'system'
が、、、およびを使用'pipe'
し ても問題がない場合は'fork'
、パイプを作成し、新しいプロセスをフォークし、パイプ内で子をリダイレクトし、子内でexecを実行し、親で結果を読み取ることができます。サンプルコードは次のようになります。'execlp'
'du'
'STDOUT'
'du'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int pfd[2], n;
char str[1000];
if (pipe(pfd) < 0) {
printf("Oups, pipe failed. Exiting\n");
exit(-1);
}
n = fork();
if (n < 0) {
printf("Oups, fork failed. Exiting\n");
exit(-2);
} else if (n == 0) {
close(pfd[0]);
dup2(pfd[1], 1);
close(pfd[1]);
execlp("du", "du", "-sh", "/tmp", (char *) 0);
printf("Oups, execlp failed. Exiting\n"); /* This will be read by the parent. */
exit(-1); /* To avoid problem if execlp fails, especially if in a loop. */
} else {
close(pfd[1]);
n = read(pfd[0], str, 1000); /* Should be done in a loop until read return 0, but I am lazy. */
str[n] = '\0';
close(pfd[0]);
wait(&n); /* To avoid the zombie process. */
if (n == 0) {
printf("%s", str);
} else {
printf("Oups, du or execlp failed.\n");
}
}
}