gpt4 book ai didi

c - wait(NULL) 函数不起作用,父进程总是在子进程之前运行

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:20 28 4
gpt4 key购买 nike

我对以下代码有疑问。它就像在 Unix 平台上使用 C 的手动 shell 程序实现。如果用户输入命令,它应该执行并返回相应的结果。如果用户在末尾输入“&”,则父进程无需等待子进程完成。

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

#define HISTORY_LIMIT 20
#define BUFFER_LIMIT 100
#define MAX_WORDS 50

int count = 0;
char history[HISTORY_LIMIT][BUFFER_LIMIT];

int tokenize(char *str, char **args, int *bRun)
{
int i, argc = 0;
char *token;
if (count == HISTORY_LIMIT)
{
// alignHistory();
}
// strcpy(history[count],str);
count++;
token = strtok(str, " \t\n");
for (i = 0; token != NULL; i++)
{
args[i] = token;
token = strtok(NULL, " \t\n");
argc++;
}

for (i = 0; i < argc; i++)
{
if (strcmp(args[i], "&") == 0)
{
*bRun = 1;
args[i] = NULL;
}
}

return argc;
} // end of tokenize function

void handleSignal(int sign)
{
if (sign == SIGINT)
{
// getHistory();
}
} // end of handlesignal

int main(void)
{
char *args[MAX_WORDS];
char buffer[BUFFER_LIMIT];
pid_t pid;
int argc;
int bgRun = 0;
if (signal(SIGINT, handleSignal) == SIG_ERR)
{
printf("can't handle ctrl-c");
return 0;
}
while (1)
{
bgRun = 0;
memset(args, 0, MAX_WORDS);
printf("osh>");
fgets(buffer, BUFFER_LIMIT, stdin);
argc = tokenize(buffer, args, &bgRun);
if (argc == 0)
continue;

if (strcmp(args[0], "exit") == 0)
break;
if (strcmp(args[0], "history") == 0)
getHistory();
// else if(strcmp(args[0],"hello")==0)printf("Hi There, How are you ?\n");
else
{
pid = fork();

if (pid == 0)
{
execvp(args[0], args);
return 0;
}
else
{
if (bgRun == 0)
wait(NULL);
}
}
}
}

输出是:

osh>whoami
root
osh>whoami &
osh>root
whoami
osh>root

但是要求的结果应该是这样的(如果命令中使用了&)

osh>whoami
root
osh>whoami &
osh>root
whoami
root
osh>

所以我使用了 bgRun int 变量并在命令有 1 时赋值为 1但那是行不通的。我认为这是 wait(NULL) 的问题。请救我脱离这个恶魔。

最佳答案

您没有说要等待哪个子进程,因此当第二个 命令退出时,第三个命令(不应该在后台执行)被认为已完成。

糟糕。

您需要处理 SIGCHLD 并在它们终止时获取后台进程,并检查退出的进程是否是您当前正在“前台”运行的进程,而不是正在完成的后台作业。 waitpid() 允许您等待特定进程。

关于c - wait(NULL) 函数不起作用,父进程总是在子进程之前运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32597332/

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