进程使用C

时间:2015-06-29 00:26:11

标签: c linux parent-child

我有四个进程A,B,C和D.A向B发送消息,向其父进程发送另一条消息:log。 进程B从A读取,检查每条消息,并根据它将消息发送到进程C或D. 流程A工作正常,其代码如下:

int main(int argc, char *argv[]){

printf("\nWritten by Nawar Youssef\n");
int i, x, fd_log[2], fd_A_B[2], fd_B_C[2], fd_B_D[2], pipe_size=250;
char ch, message_from_A[pipe_size], msg_to_B[pipe_size], msg_to_log[pipe_size], message_from_B[pipe_size], msg_to_C[pipe_size], msg_to_D[pipe_size], msg_from_log[pipe_size], temp_char[pipe_size];

pipe(fd_log);
pipe(fd_A_B);
pipe(fd_B_C);
pipe(fd_B_D);

if (fork()==0) {
    for (i=0; i < 10; i++) {
        x = (rand() % 2);
        if (x == 1)
            ch='C';
        else
            ch='D';

        //write records to A-B pipe
        sprintf(msg_to_B, "%c %d\n", ch, i);
        close(fd_A_B[READ]);
        write(fd_A_B[WRITE], msg_to_B, strlen(msg_to_B)+1);

        //write records to log pipe
        sprintf(msg_to_log, "A sent to B: %c %d\n", ch, i);
        close(fd_log[READ]);
        write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);
    }
    _exit(1);
}

但是,我正在努力让流程B按照以下方式工作:它从A读取消息,检查它是否有C或D租船人,并根据它打印一条消息显示它是否为C或D然后它向父母发送一条消息。这是代码的第一稿:

if (fork()==0) { 
    close(fd_A_B[WRITE]);
    int n_bytes = read(fd_A_B[READ], message_from_A, sizeof(message_from_A));
    for(i=0; i < pipe_size; i++) {

        //printf("%c", message_from_A[i]); //#1 

        //write a message from B to C or D pipes
        if ( message_from_A[i] == 'C') {
            printf("it is C."); //#2 

        }else if (message_from_A[i] == 'D') {
            printf("it is D."); //#3

        }else
            continue;

        //write a message to log pipe
        sprintf(msg_to_log, "B sent process C/D\n");
        close(fd_log[READ]);
        write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);

    }//for
    _exit(1);
}//if

我的问题:如果我删除了(#1)中的printf行,我就无法进入if()语句和printf(#2和#3) )。例如,这是代码的输出:

Log pipe reads from child process ( 180 ): 
A sent to B: C 0
A sent to B: C 1
A sent to B: C 2
A sent to B: D 3
and so on ...

在我从#1中删除评论之后,这是相同代码的输出:

Cit is C. 0
Cit is C. 1
Cit is C. 2
Dit is D. 3
Dit is D. 4
...
...
Log pipe reads from child process ( 250 ): 
A sent to B: C 0                   
A sent to B: C 1
A sent to B: C 2
...
...
B sent process C/D
B sent process C/D
B sent process C/D

真令人困惑!有任何想法吗?谢谢你的帮助

0 个答案:

没有答案