SW 개발

linux application / 예제코드 / fork 와 pipe 를 이용한 코딩 예제

. . . 2011. 11. 23. 11:25
반응형

fork 와 pipe 를 이용한 코딩 예제

음 pipe를 이용해서 데이터 주고받기 예제코드

정말로 우낀건 Pipe로 데이터 왔다갔다할때 단순히 int만은 안넘어 간다; ㅡㅡ;

뭐 이런 개같은 경우가;;

그래서 string 으로 넣고 다시 atoi 로 숫자로 변환시켰다.

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

int main(void){
    char buffer[BUFSIZ];
    int fd[2];
    if(pipe(fd)==-1){
        perror("pipe error..\n");
        exit(0);
    }

    pid_t pid;
    pid = fork();

    if(pid == -1){
        perror("fork error..\n");
        exit(0);
    }

    else if(pid==0){ //자식 프로세스의 경우//
        write(fd[1],"This letter is from child",BUFSIZ);
        sleep(1); //레이스 컨디션 문제 발생. 부모보다 자식이 먼저 fd에 있는 자료를
                      //가져갈 수 있으므로, 좀 쉬어준다. (fd에 있는 자료는 먼저 가져가는 사람이 임자.)
        read(fd[0],buffer,BUFSIZ);
        printf("Output of child process :: %s \n\n",buffer);
    }
    else{ //부모 프로세스의 경우//
        read(fd[0],buffer,BUFSIZ);
        printf("Output of parent process :: %s \n\n",buffer);
        write(fd[1],"This letter is from parent.",BUFSIZ);
    }

    exit(0);
}

끗.

반응형