【问题标题】:Writing to a pipe in a child process called by execl在 execl 调用的子进程中写入管道
【发布时间】:2013-10-07 20:57:00
【问题描述】:

我不明白如何在child process sp.c 中使用从mp.c 创建的pipe。当使用execl 进行外部进程时,我(我想我)似乎无法访问正确的file descriptor

   /***************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);
}

【问题讨论】:

    标签: c exec file-descriptor


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-03-04
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2011-05-05
      相关资源
      最近更新 更多