【问题标题】:C, getting a parent and child process to work using signalsC、使用信号让父子进程工作
【发布时间】:2014-12-30 00:28:56
【问题描述】:

我试图让我的子进程生成一个介于 1 -9 之间的随机数,然后将其发送到我的父进程,每次按下 control + Z 时它都会将其显示到屏幕上。我还使用 dup2() 将流从 printf 和 scanf 更改为每个进程的管道的读写端。

代码如下,按下 control C 启动主程序。现在,每次从子级发送随机数并显示在父级时,它都会等待控件 Z 被按下。我面临的问题是,当再次按下控件 Z 时,似乎孩子只运行一次,它只运行父代码。该管道也只显示相同的数字并且永远不会更改,因此它不会被更新。我还注意到,如果我在 dup 函数 printf("a \n") 之前删除 printf 行,它会打印出随机数......但是孩子运行一次的问题仍然存在。

如果有人能在这方面帮助我,我将不胜感激。干杯。

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

int selection = 0;
int secondSel = 0;
int fd[2];
int pipe1;
pid_t fork1;

void handleSignal(int sig)
{
  if (sig == SIGINT)
    {
      selection = 1;
      secondSel = 1;
    }
  if (sig == SIGTSTP)
    {
      selection = 1;
    }
}

int main()
{
int firstPipe[2];
  int secondPipe[2];

//wait for control+C
  if (signal(SIGINT, handleSignal) == SIG_ERR)
    {
    printf("Error catching signal C \n");
    exit(0);
    }

  while(1)
    {
      //wait till control c is pressed
      if (selection == 1)
    {
      signal(SIGINT, SIG_IGN);

      if (secondSel == 1)
        {
          pipe1 = pipe(fd);
        }
      if (pipe1 < 0)
        {
          printf("Error creating pipe 1 \n");
          exit(1);
        }

      if (secondSel == 1)
        {
          fork1 = fork();
        }


      if (fork1 < 0)
        {
          printf("Error with first fork. \n");
          exit(1);
        }
      else if (fork1 == 0) //first child process
        {
          signal(SIGTSTP, handleSignal);
          pause();
          printf("a \n");
          int randNum1;
          close(fd[0]);
          dup2(fd[1], 1);
          randNum1 = rand() % 9 + 1;

          printf("%d ", randNum1);
          fflush(stdout);
          close(fd[1]);
        }
      else //parent
        {
          signal(SIGTSTP, handleSignal);
          pause();
          printf("b \n");
          int f;
          close(fd[1]);
          dup2(fd[0], 0);
          scanf("%d \n", &f);
          printf("%d \n", f);
          close(fd[0]);
        }
      secondSel = 0;
    }
    }

}

【问题讨论】:

  • 如果您希望您的子进程多次接收信号,您需要在您的信号处理程序中再次注册它(例如重新启用它)。否则,信号处理程序将在每次捕获后恢复系统默认值。
  • 建议在手册页中使用sigaction 而不是signal
  • 谢谢,是的,我更喜欢使用 sigaction,但是我的讲师不希望我这样做。不是已经重新启用了吗?
  • 您无法可靠地更改标准输入和标准输出的文件描述符并使用 scanf。您需要使用readwrite 并自己处理数据。 (scanf、fread等会尝试读取一堆数据并进行缓冲,如果修改底层文件描述符,会得到意想不到的结果。)

标签: c process pipe


【解决方案1】:

评论/代码:

//wait for control+C
if (signal(SIGINT, handleSignal) == SIG_ERR)

是一个令人不安的开始。 signal() 函数为SIGINT 设置信号处理程序,但它不会等待信号到达。最简单的解决方法是在该代码块之后添加对 pause() 的调用。

在无限循环中,代码:

        if (secondSel == 1)
        {   
            pipe1 = pipe(fd);
        }   
        if (pipe1 < 0)
        {   
            printf("Error creating pipe 1 \n");
            exit(1);
        } 

次优和/或令人困惑。由于pipe1 仅在调用pipe() 时设置,因此无需在每次迭代时对其进行测试。错误消息应报告标准错误,并且不应有尾随空格。代码应该是:

        if (secondSel == 1)
        {   
            if (pipe(fd) < 0)
            {
                fprintf(stderr, "Error creating pipe 1\n");
                exit(1);
            }
        }

对保护fork()的同一个变量进行了类似的测试。

您的代码在第一个循环后小心地关闭了管道,但从不重新打开它。这就是第二次和后续迭代失败的最终原因。如果您不在每个周期都尝试做所有事情,您的代码会更好。此外,使用标准输出来调试信息会遇到各种问题;最好改用标准错误——尤其是当标准输出不能正常工作时。

仪表化代码

这是您的代码的检测版本。 err_syserr() 函数几乎是通用的;使用usleep() 的条件是此代码特有的,并确保终止错误消息的输出正常排序。我对可能失败的函数调用进行了测试——第一次关闭在第二个周期失败,因为管道描述符在第一个周期结束时全部关闭。 (请注意,在fork() 之后重用pipe() 没有任何帮助——父子节点中的管道不会相互连接。)

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

static void err_syserr(const char *fmt, ...);

int selection = 0;
int secondSel = 0;
int fd[2];
int pipe1 = 0;
pid_t fork1 = 0;

static void handleSignal(int sig)
{
    if (sig == SIGINT)
    {
        selection = 1;
        secondSel = 1;
    }
    if (sig == SIGTSTP)
    {
        selection = 1;
    }
}

int main(void)
{
    // wait for control+C
    if (signal(SIGINT, handleSignal) == SIG_ERR)
    {
        printf("Error catching signal C\n");
        exit(1);
    }
    //printf("Waiting for interrupt\n");
    //pause();

    while (1)
    {
        fprintf(stderr, "Looping: %d (%d)\n", (int)getpid(), selection);
        // wait till control c is pressed
        if (selection == 1)
        {
            signal(SIGINT, SIG_IGN);

            if (secondSel == 1)
            {
                pipe1 = pipe(fd);
                fprintf(stderr, "Created pipe: %d (%d, %d)\n", pipe1, fd[0], fd[1]);
            }
            if (pipe1 < 0)
            {
                printf("Error creating pipe 1\n");
                exit(1);
            }

            if (secondSel == 1)
            {
                fork1 = fork();
                fprintf(stderr, "Forked: %d (%d, %d)\n", fork1, (int)getpid(), (int)getppid());
            }

            if (fork1 < 0)
            {
                printf("Error with first fork.\n");
                exit(1);
            }
            else if (fork1 == 0) // first child process
            {
                signal(SIGTSTP, handleSignal);
                fprintf(stderr, "Pausing C: %d\n", (int)getpid());
                pause();
                fprintf(stderr, "Unpaused C: %d\n", (int)getpid());
                printf("a\n");
                if (close(fd[0]) != 0)
                    err_syserr("close(fd[0]=%d) failed", fd[0]);
                if (dup2(fd[1], 1) < 0)
                    err_syserr("dup2(fd[1]=%d, 1) failed", fd[1]);
                int randNum1 = rand() % 9 + 1;

                fprintf(stderr, "Print C: %d\n", randNum1);
                if (printf("%d\n", randNum1) < 2)
                {
                    fprintf(stderr, "Print C: failed\n");
                    clearerr(stdout);
                }
                fflush(stdout);
                if (close(fd[1]) != 0)
                    err_syserr("close(fd[1]=%d) failed", fd[1]);
            }
            else // parent
            {
                signal(SIGTSTP, handleSignal);
                fprintf(stderr, "Pausing P: %d\n", (int)getpid());
                pause();
                fprintf(stderr, "Unpaused P: %d\n", (int)getpid());
                printf("b\n");
                if (close(fd[1]) != 0)
                    err_syserr("close(fd[1]=%d) failed", fd[1]);
                if (dup2(fd[0], 0) < 0)
                    err_syserr("dup2(fd[0]=%d, 0) failed", fd[0]);
                int f = 99;
                if (scanf("%d", &f) != 1)
                {
                    fprintf(stderr, "Scanf P: failed\n");
                    clearerr(stdin);
                }
                printf("Parent: %d\n", f);
                if (close(fd[0]) < 0)
                    err_syserr("close(fd[0]=%d) failed", fd[0]);
            }
            secondSel = 0;
        }
    }
    return 0;
}

#include <errno.h>
#include <string.h>
#include <stdarg.h>

static void err_syserr(const char *fmt, ...)
{
    int errnum = errno;
    va_list args;
    if (fork1 != 0)     /* Parent waits 1/4 second */
        usleep(250000);
    fprintf(stderr, "%d: ", (int)getpid());
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
    if (errnum != 0)
        fprintf(stderr, ": %d %s", errnum, strerror(errnum));
    fputc('\n', stderr);
    exit(EXIT_FAILURE);
}

示例输出:

$ ./sigbug
Looping: 23528 (0)
Looping: 23528 (0)
…
…huge numbers of 'looping' messages omitted…
…
Looping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
^CLooping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
Created pipe: 0 (3, 4)
Forked: 23529 (23528, 45428)
Pausing P: 23528
Forked: 0 (23529, 23528)
Pausing C: 23529
^ZUnpaused C: 23529
Unpaused P: 23528
a
b
Print C: 5
Looping: 23529 (1)
Pausing C: 23529
Parent: 5
Looping: 23528 (1)
Pausing P: 23528
^ZUnpaused P: 23528
b
Unpaused C: 23529
23529: close(fd[0]=3) failed: 9 Bad file descriptor
23528: close(fd[1]=4) failed: 9 Bad file descriptor
$

Bug 修复代码

这是代码的修订版本,在我看来更合适的逻辑。它不包括err_syserr(),因为函数调用没有失败。不需要selectionsecondSel 变量;信号处理程序变成一个只包含return; 的存根(可以省略)。它不会在一开始就疯狂循环,因为我设置了一个暂停来等待中断。

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

static void handleSignal(int sig)
{
    return;
}

int main(void)
{
    int fd[2];
    int pipe1 = 0;
    pid_t fork1 = 0;

    if (signal(SIGINT, handleSignal) == SIG_ERR)
    {
        printf("Error catching signal C\n");
        exit(1);
    }

    printf("Waiting for interrupt\n");
    pause();
    signal(SIGINT, SIG_IGN);

    pipe1 = pipe(fd);
    if (pipe1 < 0)
    {
        fprintf(stderr, "Error creating pipe 1\n");
        exit(1);
    }
    fprintf(stderr, "Created pipe: %d (%d, %d)\n", pipe1, fd[0], fd[1]);

    fork1 = fork();
    if (fork1 < 0)
    {
        fprintf(stderr, "Error with fork.\n");
        exit(1);
    }

    fprintf(stderr, "Forked: %d (%d, %d)\n", fork1, (int)getpid(), (int)getppid());
    signal(SIGTSTP, handleSignal);

    if (fork1 == 0)
    {
        dup2(fd[1], 1);
        close(fd[0]);
        close(fd[1]);
        while (1)
        {
            fprintf(stderr, "Pausing C: %d\n", (int)getpid());
            pause();
            fprintf(stderr, "Unpaused C: %d\n", (int)getpid());
            int randNum1 = rand() % 9 + 1;
            fprintf(stderr, "Print C: %d\n", randNum1);
            if (printf("%d\n", randNum1) < 2)
            {
                fprintf(stderr, "Print C: failed\n");
                clearerr(stdout);
            }
            fflush(stdout);
        }
    }
    else
    {
        dup2(fd[0], 0);
        close(fd[0]);
        close(fd[1]);
        while (1)
        {
            fprintf(stderr, "Pausing P: %d\n", (int)getpid());
            pause();
            fprintf(stderr, "Unpaused P: %d\n", (int)getpid());
            int f = 99;
            if (scanf("%d", &f) != 1)
            {
                fprintf(stderr, "Scanf P: failed\n");
                clearerr(stdin);
            }
            else
                printf("Parent: %d\n", f);
        }
    }

    return 0;
}

示例输出:

$  ./sigbug-jl1
Waiting for interrupt
^CCreated pipe: 0 (3, 4)
Forked: 23554 (23553, 45428)
Pausing P: 23553
Forked: 0 (23554, 23553)
Pausing C: 23554
^ZUnpaused C: 23554
Print C: 5
Unpaused P: 23553
Pausing C: 23554
Parent: 5
Pausing P: 23553
^ZUnpaused C: 23554
Print C: 8
Unpaused P: 23553
Pausing C: 23554
Parent: 8
Pausing P: 23553
^ZUnpaused P: 23553
Unpaused C: 23554
Print C: 6
Pausing C: 23554
Parent: 6
Pausing P: 23553
^\Quit: 3
$

由于中断被禁用,我使用 SIGQUIT 终止程序。

【讨论】:

  • 您也可以使用sigwait 代替signal/pause
  • @Jonathan-Leffler 谢谢你,一定花了你一些时间。在我将其标记为已解决之前,我有一个问题。我决定看看使用两个孩子发送和接收随机数的结果。在父部分中,我使用 fork2 = fork() 创建了一个新的子进程。然后我做了一个 If 语句(如果 fork2 == 0),上面的代码来自 parent 放在里面。它只是停止程序?知道为什么会这样吗?
【解决方案2】:

您遇到的问题是由于在第一个数字从子级发送到父级后关闭了管道。

但是,主要问题是您的代码杂乱无章,这使得弄清楚发生了什么变得更加困难,并增加了出错的机会。我建议不要将所有内容都放在一个大循环中,而是按如下方式重构您的代码:

wait for SIGINT
create pipe
fork
if child:
    set up stdout using dup2()
    while true:
        wait for SIGTSTP
        write to pipe
else:
    set up stdin using dup2()
    while true:
        wait for SIGTSTP
        read from pipe
        etc.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多