gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:40 24 4
gpt4 key购买 nike

我有父进程需要输出子进程退出代码的任务。这个退出代码应该是子进程 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com