2014-03-04 27 views
0

你好我正在嘗試從0-9到我的孩子進程一次一個整數。在子進程內部,我將簡單地打印整數。這甚至有可能嗎?下面是我爲草稿到目前爲止,它只能打印第一0C:如何一次傳遞從父到子的整數?

if (pid >0){ 
    /*abusive parents*/ 
    if((close(fd[0])) == -1){ 
     perror("close:");} 
    int k; 
    for (k=0;k<10;k++){ 
    write(fd[1], &k, sizeof(int)); 
    } 
    close(fd[1]); 



} 
else if(pid ==0){ 
    /*stupid child*/ 

    int k; 
    if((close(fd[1])) == -1){ 
     perror("close:");} 
    read(fd[0],&k,sizeof(int)); 
    printf("k in child is %d\n",k); 
    close(fd[0]); 

} 
+1

好,我看着辦吧,我在關閉它之前需要在子進程中循環打印語句! – Pig

回答

1

編輯:以下工作

#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

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

int main(void) 
{ 
    int fd[2]; 
    pipe(fd);   
    int pid = fork(); 
    if (pid >0){ 
     /*abusive parents*/ 
     if((close(fd[0])) == -1){ 
      perror("close:");} 
     int k; 
     for (k=0;k<10;k++){ 
     write(fd[1], &k, sizeof(int)); 
     } 
     close(fd[1]); 
    } 
    else if(pid ==0){ 
    /*stupid child*/ 

    int i,k; 
    if((close(fd[1])) == -1){ 
      perror("close:");} 
    for (i=0;i<10;i++) { 
     read(fd[0],&k,sizeof(int)); 
     printf("k in child is %d\n",k); 
    } 
    close(fd[0]); 
    } 
    return 0; 
} 

輸出:

k in child is 0 
k in child is 1 
k in child is 2 
k in child is 3 
k in child is 4 
k in child is 5 
k in child is 6 
k in child is 7 
k in child is 8 
k in child is 9 
相關問題