问题描述
我被要求将消费者(客户端)开发到生产者(服务器),生产者在其中创建进程,等到消费者读取共享内存并删除进程,然后将控制权交还给生产者.终止进程并关闭共享内存块.
I've been asked to develop the consumer (client) side to a producer (server), where the producer creates processes, waits until the consumer has read shared memory and deleted processes, then passes control back to the producer for the killing of processes and the shutting down of the shared memory block.
我研究了睡眠和等待之间的区别,并且意识到,一旦fork()被调用,子进程就开始运行.
I've researched the difference between sleep and wait, and realise that as soon as fork() is called, the child process begins running.
下面的代码是在创建流程之后检查它们是否是父流程.如果是,则等待(0). *现在是我的问题,我如何知道使用者中的代码在哪里开始执行,以及如何将其传递回去? *
The below code is after the creation of processes and checks if they're parent processes. If they are, they wait(0). *Now for my question, how do I know where the code in the consumer starts to be executed, and how do I pass it back? *
else if(pid > 0)
{
wait(0);
}
下面可以看到生产者使用的主循环.
Below can be seen the main loop the producer uses.
int noToCreate = atoi(argv[2]); // (user inputs on cmd line "./prod 20 10 5" - 20 size of shared mem, 10 process to be created, 5 processes to be deleted)
while(*memSig != 2)
{
while(*memSig == 1) // set memsignature to sleep while..
{
sleep(1);
}
for(B = 0; B < noToCreate; B++)
{
pid = fork();
if(pid == -1)
{
perror("Error forking");
exit(1);
}
else if(pid > 0)
{
wait(0);
}
else
{
srand(getpid());
while(x == 0)
{
if(*randNum == 101)
{
*randNum = rand() % (100 -
1) + 1;
*pidNum = getpid();
printf("priority: %d
Process ID: %d \n", *randNum, *pidNum);
x = 1;
}
else
{
*randNum++;
*pidNum++;
}
}
exit(0);
}
} /* Closes main for loop */
if(*memSig == 0)
{
*memSig = 1;
}
} /* Closes main while loop */
感谢一群家伙:)
推荐答案
在fork之后,子进程的pid为零,因此您在调用srand函数时处于子进程中.
The pid is zero for the child process after the fork, so you are in the child process at your call to the srand function.
另一个pid是子进程的pid,它允许他的原始线程等待子进程完成.如果希望在进程之间传递数据,请考虑使用管道.一个popen调用返回两个文件描述符,一个描述符写端,另一个描述符读端.在fork和两个进程可以通信之前进行设置.
The other pid is that for the child process which allows he original thread to wait for the child to finish. If you wish to pass data between the processes consider using a pipe. A popen call returns two file descriptors, one to write end and the other to the read end. Set this up before the fork and the two processes can communicate.
这篇关于进程间通信fork()-定时wait()和/或sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!