试图将数据从执行子进程传递到c中的父进程



我一直试图使用管道来传递在子进程中计算的值(这是由执行在父进程中创建的),但一直无法弄清楚为什么数据没有被转移过来。我的理解是,除非在管道上设置close on exec标志,否则管道仍将跨进程共享,即使子进程创建了具有新堆栈,堆等的数据副本?

父进程的工作原理是允许用户输入一个值来改变一个字符串,字符串的重新赋值在子进程中完成,然后返回给父进程。

下面是父进程的代码:
if((pid = fork())) {
if(pid < 0) {
printf("Fork error: %sn",strerror(errno));
}
wait(&status);
} else {
int fd[2];
pipe(fd);
char* argv[] =  {"new string", variableToChange, NULL};
ret = execve("newstringchildprocess", argv, environ);
close(fd[1]);
int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
close(fd[0]);
}

子进程(单独的C文件):

int fd[2];
pipe(fd);
char readbuffer[100];
close(fd[0]);
printf("Enter new string: ");
write(fd[1], variableToChange, (strlen(variableToChange) + 1));
int charCount = sizeof argv[0];
variableToChange = (char*) malloc(charCount);
close(fd[1]);
wait(NULL);
exit(EXIT_SUCCESS);

目前,如果我从两个文件中删除管道代码,我只能从子进程中获得输出。任何帮助都将是伟大的

如果我理解正确的话,您需要的是将孩子的输出与父亲联系起来。

一种方法当然是管道,但是你必须在父进程中创建管道,然后再分叉,所以子进程将继承打开的管道。

哦,如果我没弄错的话,在execve之后,这个过程"终止"了。因为它不会返回到您的代码中。

int fd[2];
pipe(fd);
if((pid = fork()) < 0) {
printf("Fork error: %sn",strerror(errno));
} else if (pi==0) { //Child process
char* argv[] =  {"new string", variableToChange, NULL};
dup2(fd[1],1); //You connect to the pipe in input mode
execve("newstringchildprocess", argv, environ);
printf("Shouldn't execute thisn");
exit(1);
} else{ //Father process
int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
close(fd[0]);
close(fd[1]);
}

和其他c文件只需要关注它的逻辑,而不是通信:

printf("Enter new string: ");
printf(variableToChange, (strlen(variableToChange) + 1));
int charCount = sizeof argv[0];
variableToChange = (char*) malloc(charCount);
wait(NULL);
exit(EXIT_SUCCESS);

编辑

无论如何,您可以在dup2中替换您想要使用的文件描述符,而不是直接连接到标准输出,它可以连接到另一个fd中的管道。这有点难,但给了你更多的灵活性。请记住,在另一个。c文件中创建的另一个管道与父管道不同。

int fd[2];
pipe(fd);
if((pid = fork()) < 0) {
printf("Fork error: %sn",strerror(errno));
} else if (pi==0) { //Child process
char* argv[] =  {"new string", variableToChange, NULL};
execve("newstringchildprocess", argv, environ);
printf("Shouldn't execute thisn");
exit(1);
} else{ //Father process
int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
close(fd[0]);
close(fd[1]);
}

和其他c文件只需要关注它的逻辑,而不是通信:

printf("Enter new string: ");
write(4,variableToChange, (strlen(variableToChange) + 1)); // I put 4 as I assume it is where the input of the pipe is, as i think you can't access fd[1] form this file
int charCount = sizeof argv[0];
variableToChange = (char*) malloc(charCount);
wait(NULL);
exit(EXIT_SUCCESS);

最新更新