gpt4 book ai didi

c - C for Linux 中的进程和无限循环

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

这是我正在尝试做的事情:

Write a C program that takes an integer command line argument n, spawns n processes that will each generate a random numbers between -100 and 100, and then computes and prints out the sum of these random numbers. Each process needs to print out the random number it generates.

这是我目前所拥有的:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>


int main(int argc, char *argv[]){
int command,processCheck; // processCheck: to check if fork was successful or not and to
char * strNumProcess = NULL;// check the status of child process
while((command = getopt(argc, argv, "n:"))!=-1){
if(command == 'n'){
strNumProcess = optarg;
break;
}
}

int numProcess = atoi(strNumProcess);

int pipes[numProcess][2];


int randomNum; // Variable to store the random number
int randomNumSum=0; // Initialized variable to store the sum of random number

/** A loop that creates specified number of processes**/
for(int i=0; i<numProcess; i++){
processCheck = fork(); // creates a child process. Usually fork() = 2^n processes
if(processCheck < 0){ // Checks for the error in fork()
printf("Error");
exit(1); // Terminates with error
}
else if(processCheck == 0){
close(pipes[i][0]);
/** Child process**/
srand(time(NULL)+getpid()); // sets the randomness of the number associted with process id
randomNum = rand()% 201 + (-100); // sets the range of random number from -100 to 100 and stores the random number in randomNum
printf("%d\n" , randomNum); // Prints out the random number
write(pipes[i][1], &randomNum, sizeof randomNum);
close(pipes[i][1]);
exit(0);// Terminates successfully
}
else{
if(wait(NULL)){ // Waits for the child process to end and directs to parent process
int v;
if(read(pipes[i][0], &v, sizeof v)==sizeof(v)){
randomNumSum+=v;
close(pipes[i][0]);
}
}
}
close(pipes[i][1]);
}

printf("%d\n", randomNumSum); // Prints the sum of the random number

return 0;
}

程序在第二次处理后进入无限循环。

最佳答案

我鼓励您阅读 my answer再次非常小心。我已经提供给你使用 2 个运行示例,您所要做的就是将技术导入您的代码。

所以,您想将解决方案与管道一起使用,然后阅读再次回答。看,在我做 fork 之前,我做了这个:

if(pipe(pipes[i]) == -1)
{
perror("pipe");
pids[i] = -2; // used later for error checking
continue;
}

这会创建管道,您省略了代码中这个非常重要的部分。没有它,pipes[i] 将被取消初始化并使用 closereadwrite 在未初始化的文件描述符上是未定义的行为和任何东西可能发生:崩溃、无限循环等。

子部分还可以,父部分不太好。删除父代码像我一样加入 else 并把它放在 for 循环之外。您正在 fork 并立即等待 child 结束。什么是按顺序启动多个童工的意义无论如何,只有在之前的童工结束之后?那为什么还要用 fork 呢?

拥有童工的全部意义在于,您可以同时启动它们,这样他们同时运行并完成他们的工作。这就是 waiting 阶段的原因父进程应该所有的子进程都被创建并且启动。

同样在父 block 中你正在做 close(pipes[i][0]); 这是正确的,但随后在 if-then block 的末尾,您再次将其关闭。你不能关闭一个文件描述符两次。

我还解释了为什么在这种情况下使用 waitpid 更可靠,请使用它。你还必须确保童工正常退出。我知道在这琐碎的例子这是真的,但在更大的例子中,童工可能使用 exec 来调用其他进程,你必须确保为了从管道中读取一个正确的值,这个 child 已经正常结束。那就是 parent 期望的行为。

所以它应该是这样的:

// save ALL pids of the children!
pid_t pids[numProcess];

for(int i=0; i<numProcess; i++){
// create pipe
if(pipe(pipes[i]) == -1)
{
exit(1); // Terminates with error
}

pids[i] = fork(); // creates a child process. Usually fork() = 2^n processes
if(pids[i] < 0){ // Checks for the error in fork()
printf("Error");
exit(1); // Terminates with error
}
else if(pids[i] == 0){
/** Child process**/
// closing the reading end of the pipe
// child will only write
close(pipes[i][0]);

srand(time(NULL)+getpid()); // sets the randomness of the number associted with process id
randomNum = rand()% 201 + (-100); // sets the range of random number from -100 to 100 and stores the random number in randomNum
printf("%d\n" , randomNum); // Prints out the random number
write(pipes[i][1], &randomNum, sizeof randomNum);

// closing writing end of pipe
close(pipes[i][1]);
exit(0);// Terminates successfully
}

// PARENT

// closing writing end of pipe
// parent will only read
close(pipes[i][1]);
}

// now that all children have been launched and are running
for(int i=0; i<numProcess; i++){
int status;
if(waitpid(pids[i], &status, 0) == -1)
{
fprintf(stderr, "Cannot wait for child %d with pid: %d\n", i, pids[i]);
continue; // ignoring child
}

if(WIFEXITED(status) && WEXITSTATUS(status) == 0)
{
int v;
if(read(pipes[i][0], &v, sizeof v)==sizeof(v)){
randomNumSum+=v;
}

} else
fprintf(stderr, "Cannot read from child %d with pid: %d\n", i, pids[i]);

// close pipe even if read fails
// or child exited abnormally
close(pipes[i][0]);
}

关于c - C for Linux 中的进程和无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49098921/

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