指定コマンドを別プロセスで起動
Posted feedbacks - C
FreeBSD 6 で作成しました。fork, pipe, dup2 を使って実現しています。実行するコマンドは date です。
see: http://www.ncad.co.jp/~komata/c-kouza3.htm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define R (0)
#define W (1)
int main( void ){
char buf[1024];
int status = 0;
int pipe_c2p[2];
ssize_t read_size;
pid_t pid;
char command[] = "date";
if( pipe(pipe_c2p) == -1 ){
perror("pipe");
exit(1);
}
pid = fork();
if( pid < 0 ){ /* fail to fork */
close( pipe_c2p[W] );
close( pipe_c2p[R] );
perror("fork");
exit(1);
}
else if( pid == 0 ){ /* child process */
close( pipe_c2p[R] );
dup2( pipe_c2p[W], 1 );
close( pipe_c2p[W] );
execlp("/bin/sh", "sh", "-c", command, NULL);
}
else{ /* parent process */
close( pipe_c2p[W] );
while( (read_size = read( pipe_c2p[R], buf, sizeof(buf)-1 ) ) > 0 ){
buf[read_size] = '\0';
printf("%s",buf);
}
if( read_size == -1 ){
perror("read");
}
close( pipe_c2p[R] );
if( waitpid( pid, &status, 0 ) == -1 ){
perror("waitpid");
exit(1);
}
if( WIFEXITED(status) ){
printf("child process exit with status %d\n", WEXITSTATUS(status) );
}
}
return 0;
}
|


todogzm
#5353()
Rating4/8=0.50
与えられた文字列のコマンドを、別プロセスで実行してください。 異なるPIDのプロセスが立ち上がり、指定したコマンドを実行することが条件です。
あわせて、実行結果のリターンコードと、別プロセスが出力した標準出力を受け取る方法も記載してください。
今回投稿する上で、別プロセスとして実行するコマンドの与え方は自由ですが、実行した結果、何らかの損害を与えるようなコマンドは埋め込まないようにお願いします。
[ reply ]