【问题标题】:Check if pipe is empty, UNIX检查管道是否为空,UNIX
【发布时间】:2016-03-26 05:56:48
【问题描述】:

我有 2 个进程,父进程和子进程。父进程应该等待用户插入一些字符串,然后它应该通过管道将此字符串发送给子进程。 我已经成功地做到了这一点,但我想要实现的是检查管道是否为空,如果它是空的 60 秒,那么子进程应该向其父进程发送信号。

到目前为止我的代码:

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        char    string[100];
        char    readbuffer[80];
        pipe(fd);

        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }
        else if(childpid > 0) //parent process
        {
                close(fd[0]);
                printf ("Insert a string: ");
                scanf("%s",string);
                /* Send "string" through the output side of pipe */
                write(fd[1], string, (strlen(string)+1));
                exit(0);
        }
        else // child process
        {
                close(fd[1]);
                // check if pipe is empty for 60 seconds 
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                printf("Received string: %s", readbuffer);
        }
        return(0);
} 

【问题讨论】:

  • 将管道置于非阻塞模式,并使用select() 60秒超时。

标签: c unix ipc


【解决方案1】:

这是一个示例,其中父 sleep()s 随机数秒,然后通过管道将 write()s 发送给子。如果孩子在 5.5 秒内没有收到消息,它会向父母发送SIGUSR1,父母不写消息。这会重复指定的次数。

请注意,子进程等待 5.5 秒,而不是 5 秒,因为我们在父进程中使用了 sleep(),这需要整整几秒钟。这(通常)会留下足够的时间间隔,以避免父 sleep()s 和孩子等待 5 秒,并且他们的电线在中间交叉的情况。我们可以改为在父级中使用nanosleep(),并让子级等待整秒。

注意事项:

  1. 我们可以在子进程中使用select() 来等待指定的时间。 select() 将返回准备好的文件描述符的数量,所以如果我们只检查管道并且它返回 0,我们知道管道中没有准备好读取。

  2. 我们可以在父级中使用sleep() 来测试它。 sleep() 如果它在请求的时间内休眠,则返回 0,如果它被信号中断,则返回非零,因此我们可以检查返回值以确定它是哪种情况。对于您的特定情况,如果您希望父级从用户那里获得输入,read() 将返回 -1 并将 errno 设置为 EINTR 如果它正在等待用户输入并接收信号,因此您可以检测以这种方式超时。当然,在这个特定的用例中,父母更容易在 STDIN_FILENO 上调用 select() 本身并使用 60 秒超时,而不是让孩子在管道上等待并发送信号。

  3. 在孩子中,我们必须 FD_ZERO fd_set 并在每次循环中重新填充 struct timeval,因为 select() 可能会修改它们。

  4. 我们需要为SIGUSR1 注册一个信号处理程序(它什么都不做)以避免进程在收到时被终止。我们不需要信号处理程序来做任何事情,因为sleep() 会在它被信号中断时通过返回值告诉我们,这就是我们需要的所有信息,在这里。

代码:

#define _XOPEN_SOURCE 500

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/select.h>

#define READ_END 0
#define WRITE_END 1
#define SEC_THRESHOLD 5
#define LOOP_TIMES 5
#define BUFFER_SIZE 512

void handler(int signum)
{
    (void) signum;  //  Ignore unused argument
}

int main(void)
{
    int p[2];
    if ( pipe(p) == -1 ) {
        perror("pipe() failed");
        exit(EXIT_FAILURE);
    }

    pid_t pid = fork();
    if ( pid == -1 ) {
        perror("fork() failed");
        exit(EXIT_FAILURE);
    }
    else if ( pid == 0 ) {
        if ( close(p[WRITE_END]) == -1 ) {
            perror("failed to close pipe end in child");
            exit(EXIT_FAILURE);
        }

        for ( int i = 0; i < LOOP_TIMES; ++i ) {
            fd_set fds;
            FD_ZERO(&fds);
            FD_SET(p[READ_END], &fds);

            struct timeval timeout;
            timeout.tv_sec = SEC_THRESHOLD;
            timeout.tv_usec = 500000;

            printf("Loop %d: child waiting for %d.5 seconds.\n",
                   i, SEC_THRESHOLD);
            int status = select(p[READ_END] + 1, &fds, NULL, NULL, &timeout);
            if ( status == -1 ) {
                perror("select() failed in child");
                exit(EXIT_FAILURE);
            }
            else if ( status == 0 ) {
                printf("Loop %d: timed out in child, sending signal.\n", i);
                kill(getppid(), SIGUSR1);
            }
            else {
                char buffer[BUFFER_SIZE] = {0};
                if ( read(p[READ_END], buffer, BUFFER_SIZE - 1) == -1 ) {
                    perror("read() failed in child");
                    exit(EXIT_FAILURE);
                }
                printf("Loop %d: child read: [%s]\n", i, buffer);
            }
        }

        if ( close(p[READ_END]) == -1 ) {
            perror("failed to close read end of pipe in child");
            exit(EXIT_FAILURE);
        }

        exit(EXIT_SUCCESS);
    }
    else {
        if ( close(p[READ_END]) == -1 ) {
            perror("failed to close pipe end in parent");
            exit(EXIT_FAILURE);
        }

        struct sigaction sa;
        sa.sa_handler = handler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        sigaction(SIGUSR1, &sa, NULL);

        srand((unsigned) time(NULL));

        for ( int i = 0; i < LOOP_TIMES; ++i ) {
            const char * msg = "Message to child";
            const int wait_time = rand() % 6 + 3;

            printf("Loop %d: parent waiting for %d seconds...\n", i, wait_time);
            int status = sleep(wait_time);
            if ( status == 0 ) {
                printf("Loop %d: parent sending message to child.\n", i);
                if ( write(p[WRITE_END], msg, strlen(msg)) == -1 ) {
                    perror("write() error in parent");
                    exit(EXIT_FAILURE);
                }
            }
            else {
                printf("Loop %d: parent interrupted by signal.\n", i);
            }
        }

        if ( close(p[WRITE_END]) == -1 ) {
            perror("failed to close write end of pipe in parent");
            exit(EXIT_FAILURE);
        }

    }

    if ( waitpid(pid, NULL, 0) == -1 ) {
        perror("waitpid() failed");
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}

和示例输出会话:

paul@horus:~/src/sandbox$ ./sigpipe
Loop 0: parent waiting for 7 seconds...
Loop 0: child waiting for 5.5 seconds.
Loop 0: timed out in child, sending signal.
Loop 1: child waiting for 5.5 seconds.
Loop 0: parent interrupted by signal.
Loop 1: parent waiting for 7 seconds...
Loop 1: timed out in child, sending signal.
Loop 2: child waiting for 5.5 seconds.
Loop 1: parent interrupted by signal.
Loop 2: parent waiting for 6 seconds...
Loop 2: timed out in child, sending signal.
Loop 3: child waiting for 5.5 seconds.
Loop 2: parent interrupted by signal.
Loop 3: parent waiting for 5 seconds...
Loop 3: parent sending message to child.
Loop 4: parent waiting for 3 seconds...
Loop 3: child read: [Message to child]
Loop 4: child waiting for 5.5 seconds.
Loop 4: parent sending message to child.
Loop 4: child read: [Message to child]
paul@horus:~/src/sandbox$ 

因此我们可以看到,如果子级达到其 5.5 秒超时,则父级每次迭代都会中断,并在所有其他情况下成功发送消息。

【讨论】:

    猜你喜欢
    • 2022-12-16
    • 2012-09-14
    • 2012-11-28
    • 1970-01-01
    • 2016-08-08
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多