我是fork()和创建4个同时运行的子进程(忙于工作),但父进程需要等到所有子进程退出。 我觉得我可以用更好的方式编码...任何建议或看起来好吗? (我需要保留2种形式和主要格式)
using namespace std;
void simulateBusyWork(char, pid_t);
pid_t performFork();
int main()
{
srand(time(NULL));
performFork();
return 0;
}
pid_t performFork() {
pid_t pid;
//create four child processes
for (int i = 0; i < 4; ++i) {
pid = fork();
if (pid<0) {
continue;
} else if (pid == 0) {
break;
}
}
//fork failed
if (pid < 0) {
fprintf(stderr, "Fork failed./n");
return 1;
}
//child process do busy work
else if (pid == 0) {
cout << "A child process with PID " << getpid() << " was created." << endl;
pid = getpid();
simulateBusyWork('C', pid);
_exit(0);
}
//parent process do busy work
else if(pid > 0){
simulateBusyWork('P', getpid());
//parent process waits for children to exit
int status, exited;
//print which child has exited
for (int i = 0; i < 4; i++) {
exited = waitpid(-1, &status, 0);
cout << "P" << getpid() << ": Process " << exited << " has exited." << endl;
}
}
return pid;
}
void simulateBusyWork(char ch, pid_t pid) {
for (int i=0 ; i < 4; i++) {
cout << ch << pid << ": " << i << endl;
//if (i < 4)
sleep(1);
}
cout << "Process " << ch << pid << " has finished its work." << endl;
}
答案 0 :(得分:0)
from django.db.models import *
from django.contrib.auth.models import User, Group
from django.db.models.signals import post_save
class MyUser(Model):
user = OneToOneField(User, primary_key=True)
Volume = IntegerField(default=5*1024*1024)
def create_profile(sender, instance, created, **kwargs):
if created:
profile, created = MyUser.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User, dispatch_uid="create_profile")
:
电话
man waitpid
是等效的 到:wait(&status)
所以你可以简化一下。