【问题标题】:how can I print the exit status inside of the code?如何在代码中打印退出状态?
【发布时间】:2021-05-17 22:51:09
【问题描述】:

如何在父进程中打印子程序的退出状态? (等待()之后)

获取子进程退出状态的代码有效,但不知道之后如何打印

#include <stdio.h>   // printf
#include <unistd.h>  // getpid
#include <stdlib.h>

void childProcess(void);
void fatherProcess(int childpid);

int num1, num2, oper_inizializzata;

int main() {

  int pid=fork();
  if (pid==0) {
    childProcess();
  } else if (pid>0) {
    fatherProcess(pid);
  } else { // pid<0
    printf("Creazione del processo figlio fallita!\n");
  }
}

void childProcess(void)
{
  printf("Inserisci il valore del primo numero\n");
  scanf("%d",&num1);
  printf("Inserisci il valore del secondo numero\n");
  scanf("%d",&num2);
  printf("Scegli tra 1 o 2 per il valore della variabile\n");
  scanf("%d",&oper_inizializzata);
  
  if(oper_inizializzata==1){
    int num1piu2=num1+num2;
    printf("num1 + num2 e' %d\n", num1piu2);
    exit(num1piu2);
  }
  else if(oper_inizializzata==2){
    int num1per2=num1*num2;
    exit(num1per2);}
}

void fatherProcess(int childpid)
{
  wait();
  //print exit status here
}

【问题讨论】:

  • 获取子进程退出状态的代码有效。我没有看到任何代码来获取子进程的退出状态。你能指出来吗?
  • @kaylum 这就是问题所在;它还没有。 OP 想知道在fatherProcess 中做什么来获得等待孩子的退出状态。
  • 请阅读wait manual。它甚至有一个示例,可以完全按照要求进行操作。
  • @WhozCraig:问题说明“获取子进程退出状态的代码有效”,暗示 OP 确实有获取退出状态的代码,但由于它没有出现在问题中,他们没有向我们展示。
  • 这能回答你的问题吗? Capturing exit status code of child process

标签: c unix operating-system system-calls


【解决方案1】:

来自waitman页面

pid_t 等待(int *wstatus);

如果 wstatus 不为 NULL,wait() 和 waitpid() 存储状态信息 在它指向的 int 中。这个整数可以用 以下宏(将整数本身作为参数,而不是 指向它的指针,就像在 wait() 和 waitpid() 中所做的那样!):

...

例如:

void fatherProcess(int childpid)
{
  int status;
  pid_t pid;
  pid = wait(&status);

  if (pid == -1) {
    perror("wait");
    // handle this case 
  }
  if (WIFEXITED(status)) {
    printf("Child %ld exited successfully", pid_t);
  }
  // Handle the rest of the status cases accordingly
}

【讨论】:

    【解决方案2】:

    您可以使用waitpid() 获取子进程的退出状态。

    例子:

    void fatherProcess(int childpid)
    {
        int status;
        waitpid(childpid,&status,0);
        if(WIFEXITED(status)){
            print("exit status of child=%d\n",WEXITSTATUS(status));
        }
        return;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      相关资源
      最近更新 更多