-2
부모와 자식 간의 의사 소통을 이해하려고합니다. 면책 조항 : 다음은 프로세스 내 의사 소통을 이해하기 위해 교수님이 제공 한 샘플 코드입니다. 내 약점은 파일 설명자에 있습니다. 나는 파이프 (int array [2])가 std에 배열 [0] = fd를 만들고 std에 배열 [1]을 만드는 것을 이해합니다. 그러나이 둘 사이의 의사 소통은 어떻게 이루어지고 있습니까? 나는 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]);
}
나머지 코드를 추가해야합니다. 'childproc'도 사용되지 않으며, 문자열로 정의됩니다. 'main'은 구현되지 않았고 이후에 세미콜론이없는 유효한 forward 선언이 아닙니다 ..'p1.c'를 게시하십시오 –
'main'의 나머지 부분은 어디입니까? ... – dasblinkenlight
in the main은 execv를 호출 한 다음 – teamaster