gpt4 book ai didi

c - 写入由 execl 调用的子进程中的管道

转载 作者:行者123 更新时间:2023-11-30 17:46:31 27 4
gpt4 key购买 nike

我不明白如何在子进程 sp.c 中使用从mp.c 创建的管道。当使用 execl 进行外部进程时,我(认为我)似乎无法访问正确的文件描述符

   /***************mp.c*****************/ 

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[]) {
char *procpath = "/mypath/sp";
char *procname = "sp";
pid_t pid;
int fd[2];
int ret;
char buf[20];
memset(&buf[0], 0, sizeof(buf));
ret = pipe(fd);
if(ret == -1){
perror("pipe");
exit(1);
}
pid = fork();
printf("%d\n",pid);
if (pid == 0){
//dup2(mypipefd[1],STDOUT_FILENO);
ret = execl(procpath, procpath, "1","2",NULL);
perror("execl failed to run slave program");
exit(1);
}
else if (pid > 0){
/* Parent process*/
printf("execl ret val = %d",ret);
printf("Parent process \n");
close(fd[1]);
read(fd[0],buf,15);
// close(fd[1]);
close(fd[0]);
printf("buf: %s TEST\n", buf);
printf("buf: %s TEST\n", buf);
}
else{
printf("call to fork failed, no child\n");
exit(-1);
}
exit(0);
}

以及创建的进程...

/***************sp.c*****************/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[]){
int ret;
//printf("Child process \n");
int fd[2];
pipe(fd);
//dup2(fd[1],1);
//int out;
/*ret = dup2(fd[1],1);
if (ret = -1){
printf("%s\n", strerror(errno));
};*/
//sprintf()
//printf("%d\n", ret);
//mypipefd = argv[1];
printf("Child process \n");
//close(fd[0]);
write(fd[1], "Hello there!",12);
close(fd[1]);
exit(0);
}

最佳答案

问题是您在每个应用程序中创建不同的管道。为了通过管道正确通信,两个程序应共享同一管道(由管道函数创建的文件描述符之一)。

基本上要解决这个问题,您必须在一个应用程序中创建管道并将文件描述符发送到另一个程序,而无需再次调用系统调用管道。可以使用套接字 unix 域将文件描述符发送到另一个进程。看一下这个帖子Can I share a file descriptor to another process on linux or are they local to the process?

关于c - 写入由 execl 调用的子进程中的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19234612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com