如何创建多个流程

时间:2012-01-04 22:24:43

标签: c linux process fork

我需要创建5个进程(而不是线程)并使用信号量在它们之间进行同步。同步算法将类似于“Round Robin”。问题是如何创建5个流程?我可以这样做吗?

pID = fork();

if(pID < 0) {
    fprintf(stderr, "Fork Failed");
    exit(-1);
}
else if(pID == 0) {
    pID = fork();

    if(pID < 0) {
    fprintf(stderr, "Fork Failed");
    exit(-1);
    }
    else if (pID == 0) {
        pID = fork();

        if (pID < 0) {
            fprintf(stderr, "Fork Failed");
            exit(-1);
        } else if (pID == 0) {
            pID = fork();

            if (pID < 0) {
                fprintf(stderr, "Fork Failed");
                exit(-1);
            } else if (pID == 0) {                    
                /* Process 5 */
                printf("process5 is running... id: %d\n", pID);                    
            } else {
                /* Process 4 */
                printf("process4 is running... id: %d\n", pID);
            }
        } else {
            /* Process 3 */
            printf("process3 is running... id: %d\n", pID);
        }
    }
    else {
        /* Process 2 */
        printf("process2 is running... id: %d\n",pID);
    }
}
else {
    /* Process 1 */
    printf("process1 is running... id: %d\n",pID);

    return (EXIT_SUCCESS);
}

1 个答案:

答案 0 :(得分:4)

是的,但是其他人可以更容易阅读和理解循环。

int
call_in_child(void (*function)(void))
{
    int pid = fork();
    if (pid < 0) {
        perror("fork");
        return 0;
    }
    if (pid == 0) {
        (*function)();
        exit(0);
    }
    return 1;
}

然后在其他地方

for (i = 0; i < 4; i++) {
    if (! call_in_child(some_function)) {
        ... print error message and die...
    }
}
some_function();

并将你的程序的内容放在some_function中。