c - 将子进程数共享给父进程。 Exit() 和 Wait() 或全局变量

标签 c linux

我有父进程需要输出子进程退出代码的任务。这个退出代码应该是子进程 id 的总和,加上一个变量 k 和整体的模 100。我尝试了两种方法来保存子进程的退出代码:

  • 在子进程中退出(退出代码)并使用 wait() 在父进程中保存。你应该在评论中保留这个
  • 将退出码保存在全局变量中,并在父进程wait()后输出退出码

但是,两者都不起作用。你能帮我实现它吗?谢谢!

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

//globale Variable
int out;

int main()
{
//Nutzereingabe von k:
int k=0;
scanf("%d",&k);
    //Erzeugen eines Kindprozesses:
    if(fork()==0)
    {
        //Kindprozess liegt vor
    int zaehler=1;
    char ausgabe[256]={0};
    while(zaehler<=k){
        //printf("%d\t"
        int pid=getpid();
        int ppid=getppid();
        sprintf(ausgabe, "%d %c %d %c %d\n", pid,' ', ppid,' ',zaehler);
        write(STDOUT_FILENO, ausgabe, strlen(ausgabe));
        sleep(1);
    zaehler++;
    }   
    //write(STDOUT_FILENO, (getpid()+k)%100, strlen((getpid()+k)/100));
    //printf("%d\n", (getpid()+k)%100);
    out=(getpid()+k)%100;
    printf("%i", out);
    exit((getpid()+k)%100);
 }
    else
    {
        //Elternprozess liegt vor
        time_t curtime;
        time(&curtime);
        printf("Start: %s", ctime(&curtime));

    }
    //int exitcode=wait(NULL);
    wait(NULL);
    //exitcode to String casten:
    char str[24];
    sprintf(str, "Exit-Code: %i\n", out);
    //Ausgabe und exitcode zu einem String zusammenfuegen: (vorher concat())
    //char* s = concat("Exit-Code: ", str);
    //strncat(*str,"Exit-Code: ",str);
    //Ausgabe des Exitcodes:
    write(STDOUT_FILENO, str, strlen(str));
    time_t curtime;
    time(&curtime);
    printf("Ende: %s\n", ctime(&curtime));
    return 0;
}

最佳答案

来自 man wait :

pid_t wait(int *status);

If status is not NULL, wait() and waitpid() store status information in the int to which it points.

WEXITSTATUS(status) returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) ....

所以使用:

}
// warte fur unserer kind
int exitstatus;
wait(&exitstatus);
// caste exitcode to string casten
char str[24];
sprintf(str, "Exit-Code: %d\n", WEXITSTATUS(exitstatus));

关于c - 将子进程数共享给父进程。 Exit() 和 Wait() 或全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53414146/

相关文章:

c - 使用 NCurses 和 C 来显示系统信息的简单文本 GUI (TUI)

java - 使用非常高的 CPU 和内存的 Elasticsearch Java

python - 将程序作为可执行文件运行时设置默认 python 版本 ./xxx.py - 在 linux 上

linux - 用户数据 (cloud-init) 脚本未在 EC2 上执行

linux - 在 RabbitMQ 崩溃后有没有办法拯救队列?

c - 后台进程和挂起进程 - 在 C 中实现作业控制 Shell

c - for循环不运行

linux - 将多个 cpanel 帐户压缩到单独的 .tar.gz 文件中

c - 如何检查指向结构数组的指针在c中是否为空?

无法从代理获取 QUERY_STRING 到应用程序