停止子进程重复输出而不杀死

时间:2018-05-10 08:31:09

标签: c multiprocessing parent-child interprocess

我有一个父进程接收可以创建子进程的用户输入,然后通过进一步的输入来操作各个子进程。

应该打印的内容如下:

New Locker Created: 1

New Locker Created: 2

New Locker Created: 3

New Locker Created: 4

New Locker Created: 5

但我得到以下内容:

New Locker Created: 1

New Locker Created: 2

New Locker Created: 3

New Locker Created: 4

New Locker Created: 5

New Locker Created: 5

New Locker Created: 4

New Locker Created: 5

New Locker Created: 5

New Locker Created: 3

New Locker Created: 4

New Locker Created: 5

这继续了几行,但这就是想法。据我所知,这是因为子进程继续执行,因为父进程在接收新输入时一直在等待其他子进程完成。这是对的吗?

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include "locker.h"
#include <signal.h>
#include <stdarg.h>

#define P1_READ 0
#define P2_WRITE 1
#define P2_READ 2
#define P1_WRITE 3

#define NUM_PIPES 2

pid_t this_pid;

int main(){

char buffer[100];

int locker_count = 0;
int fd[2*NUM_PIPES];
int len = 0, i;
pid_t pid_list[100], wpid;

memset(pid_list,0,100);

pid_t this_pid;
struct locker_t new_locker = { .id = 0, .user_id = 0, .locked = 1, .owned = 0};

fflush(stdout);

while(1){
    scanf("%s", buffer);

    fflush(stdout);

    if(strcmp(buffer, "CREATE") == 0){

        for(i = 0; i < NUM_PIPES; ++i){
            if(pipe(fd+(i*2)) < 0){
              perror("Failed to allocate pipes");
              exit(EXIT_FAILURE);
            }
        }

        fflush(stdout);

        this_pid = fork();

        if(this_pid == 0){

            //close descriptors we don't need in this process
            close(fd[P1_READ]);
            close(fd[P1_WRITE]);

            len = read(fd[P2_READ], &locker_count, sizeof(locker_count));

            //increase by 1
            locker_count++;

            //create locker
            new_locker.id = locker_count;

            printf("New Locker Created: %d\n", locker_count);
            printf("\n");

            write(fd[P2_WRITE], &locker_count, sizeof(locker_count));

            //finished. close remaning descriptors
            close(fd[P2_READ]);
            close(fd[P2_WRITE]);

            //need to stop this process for further executing

        }
        if(this_pid > 0){

            //close unneeded descriptors
            close(fd[P2_READ]);
            close(fd[P2_WRITE]);

            write(fd[P1_WRITE], &locker_count, sizeof(locker_count));

            //now wait for response
            len = read(fd[P1_READ], &locker_count, sizeof(locker_count));

            //pid_list[(locker_count-1)] = this_pid;

            close(fd[P1_READ]);
            close(fd[P1_WRITE]);            

            fflush(stdout);

            while ((wpid = waitpid(this_pid, NULL, 0)) > 0); 

        }
    }

    if(strcmp(buffer, "QUIT") == 0){
        break;
        exit(0);
    }
}
}

感谢您的帮助:)

0 个答案:

没有答案