Process 如何在父进程或子进程中停止程序?
我开发了这段代码,只是为了解决我在开发的另一个大型程序中遇到的问题Process 如何在父进程或子进程中停止程序?,process,fork,kill,fflush,Process,Fork,Kill,Fflush,我开发了这段代码,只是为了解决我在开发的另一个大型程序中遇到的问题 #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <cstring> #include <cstdlib> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #incl
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <limits.h>
#include <string>
#include <iostream>
using namespace std;
void processLine (char []);
void readLine(char []);
const int LIMIT = 512;
int main(int argc, char *argv[])
{
char oneLine[LINE_MAX];
readLine(oneLine);
return 0;
}
void readLine(char line[])
{
processLine(line);
//Otherstuff
------------
}
void processLine(char line[])
{
pid_t process;
int child_status;
string input;
cout << "Input: ";
cin >> input;
process = fork();
if(process == 0)
{ // do nothing
}
else
{
//parent
if(input == "quit")
{
printf("Quit command found ! \nExiting ");
for(int i = 0;i < 3;i++)
{
printf(".");
fflush(stdout);
sleep(1);
}
printf("\n");
exit(0);
}
else
{
wait(&child_status);
}
}
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
void processLine(char[]);
无效读线(字符[]);
常数int LIMIT=512;
int main(int argc,char*argv[])
{
char oneLine[行最大值];
读线(单线);
返回0;
}
无效读取行(字符行[])
{
生产线;
//其他东西
------------
}
无效进程行(字符行[])
{
pid_t过程;
国际儿童基金会地位;
字符串输入;
cout>输入;
进程=fork();
如果(进程==0)
{//什么也不做
}
其他的
{
//母公司
如果(输入=“退出”)
{
printf(“找到退出命令!\n退出”);
对于(int i=0;i<3;i++)
{
printf(“.”);
fflush(stdout);
睡眠(1);
}
printf(“\n”);
出口(0);
}
其他的
{
等待(&child_状态);
}
}
}
我的目标很简单,当用户输入quit时
我只是展示一下
找到退出命令
正在退出..
这三个点之间各有一秒的延迟
然而,我得到的结果是
找到退出命令
退出。其他东西..
然而,似乎发生的是父进程返回并执行调用函数中的其他内容,然后再继续打印其他两个点。如何避免父进程这样做?使用waitpid()如下:
pid_t childPid;
childPid = fork();
...
int returnStatus;
waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate.
在这里使用它
if(childPid == 0) // fork succeeded
{
// Do something
exit(0);
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
waitpid(childPid, &returnStatus, 0);
}
@Olaf这主要是cAnd,程序中的人为延迟总是会引起用户的不安,并加重用户的情绪。我想说(如果用户输入“退出”),孩子“返回,然后从调用函数中执行其他内容”这是子进程打印<代码>其他东西< /> >:返回代码< > For < /C> >子>代码> 0 / <代码>,您的<代码> /不做任何< /代码>,然后存在“代码> PrimeLoo> <代码>,继续执行<代码>其他的东西。相似的语法并不意味着相同的语义。除非它是用C编译器编译的,否则它不是C。我应该在何处执行此操作?在主进程中,在fork之后