2010-11-08 109 views
0

我在使用linux中的管道時遇到了問題。我的工作是這樣的:在C使用管道進行過程通信

寫一個程序,這將創建一個孩子。子進程將使用管道與父進程進行通信。父進程會給出一個0 = y之間的隨機數,然後父親會向用戶詢問他的名字,他會像這樣發佈它(George - > egroeG)。

我的代碼如下:

#include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 
    #include <signal.h> 
    #include <unistd.h> 
    #include <fcntl.h> 

void myalarm(int sig) { 
printf("\nTime is out. Exiting...\n"); 
exit(0); 
} 
int main(int argc, char **argv){ 

    int x, x1, n, m, pid, fd1[2]; 
    int y = rand() % 100 + 2; 
    int i=0; 
    char *name, *arxi; 

if (pipe(fd1) == -1) { 
    perror("ERROR: Creating Pipe\n"); 
    exit(1); 
} 
    pid = fork(); 
    switch(pid) { 
    case -1: 
    perror("ERROR: Creating Child Proccess\n"); 
    exit(99); 
    case 0: 
    close(fd1[0]); /*Writer*/ 
    printf("\nGive a number between 1 & 100:\n"); 
    scanf("%d", &x); 

    n = write(fd1[1], x, 1); 
/*dup2(fd1[0],0);*/ 
     while (x < 0 || x > 100) { 
     printf("ERROR:You gave a wrong number..."); 
     printf("\nGive a number between 1 & 100:\n"); 
     scanf("%d", &x); 
     } 
    close(fd1[1]); 
    break; 
    default: 
    close(fd1[1]); /*Reader*/ 
    printf("I Am The Father Process...\n"); 
    printf("y = %d\n", y); 

    m = read(fd1[0], x1, 0); 
/*dup2(fd1[1],1);*/ close(fd1[0]); 

     if (x1 < y) { 
     kill(pid, SIGTERM); //termination of the child process 

     } 
     else { 
     signal(SIGALRM, myalarm); 
     printf("Please, type in your name:\n"); 
     fflush(stdout); 
     alarm(10); //Start a 10 seconds alarm 
     scanf("%s", name); 
     arxi = name; 
     alarm(0); 
     while(*name != '\0') { 
     name++; 
     } 
     name--; 
     while(name >= arxi) { 
     putchar(*name); 
     name--; 
     } 
     printf("%s\n", name); 
     } 
    wait(&pid); 
    break; 
    } 
return 0; 
} 
+1

因爲我的英語不是那好,給我一些東西在c。 – Konst 2010-11-08 14:26:09

+1

看起來像功課嗎? – 2010-11-08 14:27:59

+0

請編輯您的文章並將所有代碼放入代碼格式。 – 2010-11-08 14:28:32

回答

0

可能有其他的問題,但這些跳出的錯誤:

n = write(fd1[1], x, 1); 

這會寫從地址x 1個字節,這將可能會崩潰。你想:

n = write(fd1[1], &x, sizeof(x)); 

同樣的,這是要讀取0字節,以解決X1,它不會做任何事情:

m = read(fd1[0], x1, 0); 
你想

m = read(fd1[0], &x1, sizeof(x1)); 
+0

多數民衆贊成的正確的感謝....但如果x1 Konst 2010-11-08 15:08:25

+0

謝謝你們。你是一個很好的幫助;) – Konst 2010-11-08 15:28:57

相關問題