私は学校のプロジェクトに取り組んでいますが、それを解決しようとしている方法が可能かどうかさえわかりません。このプロジェクトでは、プログラムを作成し、2 つの子をフォークして、pid を他のプログラムに置き換える必要があります。2 つの子は、read() と write() を使用してパイプを介して話します。
私が持っている質問は、execve を使用してパイプをその子に渡すことです。私が今持っているのはこれです:
親プログラム - fork し、子に execve を呼び出す:
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUF_SIZE 16
/* 2 cmd line arguments
1. file already in system (to be copied)
2. file to be created (the copy)
create pipe (for communication) + 2 child processes
first child replace pid with reader
second child with writer
wait for both children to terminate before exiting
*/
int main(int argc, char* argv[]){
//making the pipe
int pfd[2];
pipe(pfd);
int num_dead;
//forking
pid_t reader_child_pid;
pid_t writer_child_pid;
pid_t child_pid;
//args for each fork
char *args_1[] = {argv[1], (char *) 0};
char *args_2[] = {argv[2], (char *) 0};
switch(writer_child_pid = fork()) {
case -1:
perror("fork failed");
return 1;
case 0:
close(pfd[1]);
dup2(pfd[0], 0);
execve("./writer", args_2, NULL);
perror("execve failed");
break;
default:
switch(reader_child_pid = fork()) {
case -1:
perror("2nd fork failed");
return 1;
case 0:
close(pfd[0]);
dup2(pfd[1], 1);
execve("./reader", args_1, NULL);
perror("execve failed");
break;
default:
//close(pfd[0]);
//close(pfd[1]);
break;
}
}
num_dead = 0;
for(;;) {
if((child_pid=wait(NULL)) == -1){
if(errno == ECHILD) {
printf("NO MORE CHILDREN");
exit(0);
} else {
perror("wait error");
exit(1);
}
}
++num_dead;
printf("wait() returned 1 child");
}
}
dup2 を使用して stdin および stdout にリダイレクトしようとしています。次に、子供たちで、次のように標準出力と標準入力を読み書きしようとします。
子 - stdin からのデータの読み取り
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define BUF_SIZE 16
int main(int argc, char* argv[]){
printf("\n\nWRITER\n");
/* ready to process info
read the file, write it to pipe */
int wri_inFile = open(argv[0], O_WRONLY | O_CREAT | O_TRUNC | S_IRUSR | S_IWUSR);
char buf[BUF_SIZE];
int read_test;
for(;;) {
read_test = read(0, buf, BUF_SIZE);
if(read_test == 0) //eof
break;
write(wri_inFile, buf, BUF_SIZE);
}
close(wri_inFile);
exit(0);
}
あなたの提案に従ってdupを使用していますが、本来あるべきようにstdinとstdoutにアクセスしているかどうかはわかりません。
--参考までにもう一人の子です。
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define BUF_SIZE 16
int main(int argc, char* argv[]){
printf("\n\nREADER\n");
/* ready to process info
read the file, write it to pipe */
printf("FILE::%s", argv[0]);
int inFile = open(argv[0], O_RDONLY);
char buf[BUF_SIZE];
int read_test;
for(;;) {
read_test = read(inFile, buf, BUF_SIZE);
if(read_test == 0) //eof
break;
write(1, buf, BUF_SIZE);
}
close(argv[0][1]);
close(inFile);
printf("\nDONE WITH READER\n");
exit(0);
}
--違いがある場合は、他の子 (パイプに書き込んでいる子) が正常に書き込んでいるように見えますが、上の子はパイプから読み取ることはなく、上の outFile は常に空です。
* *まだ同じことが起きている
私はあなたが私のために問題を解決してくれることを望んでいるわけではありません。ありがとうございました。
私は積極的に作業する例を探していますが、私の問題が今どこにあるのかを実行する子からのコードを示すものは見つかりません。