2012-09-15 64 views
-2

我想了解父與子之間的通信。免責聲明:以下是我的教授在課堂上提供的用於瞭解進程間通信的示例代碼。我的主要弱點是文件描述符。我知道pipe(int array [2])使std in和array [1]的array [0] = fd爲std out。但是這兩者之間的溝通如何?我對CS很新。謝謝!與管道的子父進程間通信

/* 
* This program demonstrates the use of pipes for interprocess communication. 
* The parent process creates a pipe using the "pipe" system call. It then 
* creates a child process and passes the child a file descriptor for one side 
* of the pipe. It then writes a name to its side of the pipe and waits for the 
* child to print a message incorporating the name. 
* 
* Before you attempt to run this program, be sure you've compiled the program 
* named "hw3b.c" and have the executable in a file named "hw3b". 
*/ 

#include <stdlib.h> 
#include <strings.h> 
#include <stdio.h> 

/* 
* The name of the file we plan to run. It's here in a define so that we can 
* change it easily 
*/ 
#define CHILDPROCNAME "hw3b" 

/* 
* The behavior of main() is specified by the previous comment 
*/ 

int main(char* argv) 
{ 
    // store the ids of the two file descriptors that serve as the pipe 
    int mypipe[2]; 

    // make the pipe 
    pipe(mypipe); 

    // child code: 
    if (fork() == 0) { 
     // execv requires us to create a full invocation, consisting of the 
     // string name of the program to run, a string for each command-line 
     // argument, and then a null string. We store all that in this array of 
     // strings 
     char* myargv[3]; 

     // we use this to turn an int into a string 
     char buf[50]; 

     // set up the name of the program to run 
     myargv[0] = calloc(strlen(CHILDPROCNAME) + 1, sizeof(char)); 
     strcpy(myargv[0], CHILDPROCNAME); 

     // write one of the pipe's fds to the second parameter 
     sprintf(buf, "%d", mypipe[0]); 
     myargv[1] = calloc(strlen(buf) + 1, sizeof(char)); 
     strcpy(myargv[1], buf); 

     // third param is null 
     myargv[2] = 0; 

     // switch to child process 
     execv(CHILDPROCNAME, myargv); 

     // NB: this should use fprintf and write to stderr 
     printf("Uh oh, execv didn't work!\n"); 

     // crash on failure 
     exit(-1); 
    } 

    // parent code 
    else { 
     // status variable for storing the result of waitpid 
     int status; 

     // Send a string across the pipe to the child process 
     write(mypipe[1], "Kerry", strlen("Kerry")); 

     // wait for the child process to finish 
     waitpid(-1, &status, 0); 

     // NB: we should use status! 
    } 

    // close our half of the pipe 
    close(mypipe[1]); 
} 
+3

您需要添加其餘的代碼。 'childproc'甚至沒有被使用,它被定義爲一個字符串。 'main'沒有實現,甚至沒有一個有效的前向聲明,沒有分號後..請發佈'p1.c' –

+0

'main'的其餘部分在哪裏?... – dasblinkenlight

+0

IN主要是如果準備參數爲childprocess調用execv然後調用它 – teamaster

回答

1

它只是在你的p1替代方案childproc。他可能意味着它取決於價值,即p1