我对 C 还比较陌生,我目前正在尝试编写一个并发进程程序,但是每当我进入子进程时,它只打印出 Printf 语句的一部分,如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int concurrent(int num, int numOfProcs, int *nump)
{
pid_t pid;
pid = fork();
if (pid < 0)
{
perror("There was an error during fork call: ");
exit(1);
}
//child Processes
if (pid == 0)
{
for (int i = 0; i < numOfProcs; i++)
{
printf("\nBEFORE Increment, ");
printf(" \nChild number: %d",i);
printf(" \nChild process ID: %d",(int) getpid());
printf(" \nCurrent value of num: %d", num);
printf(" \nCurrent value of nump: %d", *nump);
printf(" \nCurrent value of x: %d", x);
x += 5;
num ++;
*nump++;
printf("\nAFTER Increment, ");
printf(" \nChild number: %d",i);
printf(" \nChild process ID: %d",(int) getpid());
printf(" \nCurrent value of num: %d", num);
printf(" \nCurrent value of nump: %d", *nump);
printf(" \nCurrent value of x: %d", x);
}
exit(0);
}
//parent process
else
{
for(int i = 0; i < numOfProcs; i++)
{
wait(NULL);
printf("\nChild Process ended, Child PID: %d",(int) getpid());
}
}
}
int main (int argc, char *argv[])
{
char *a = argv[1];
int numOfProcs = atoi(a);
x = 10;
int num = 50;
int *nump = malloc(100);
*nump = 100;
printf("\nCurrent Values");
printf("\nNumber of processes: %d",numOfProcs);
printf("\nCurrent value of num: %d", num);
printf("\nCurrent value of nump: %d", *nump);
printf("\nCurrent value of x: %d", x);
concurrent(num,numOfProcs,&nump);
exit(0);
}
这是现在的输出:
Current Values
Number of processes: 2
Current value of num: 50
Current value of nump: 100
Current value of x: 10
BEFORE Increment,
Child number: 0
Child process ID: 35148
Current value of x: 10
Child Process ended, Child PID: 35147
Child Process ended, Child PID: 35147
我只是有点困惑为什么它不输出“AFTER Increment”和其余的打印语句,任何帮助将不胜感激。
使用
-Wall
构建二进制文件时会发现一些问题:
x
未初始化*nump++
:the value is not used
(因为您增加了指针nump
,而不是它所指向的值 - 并且然后取消引用指针,请参阅运算符优先级)这是修复后的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int concurrent(int num, int numOfProcs, int *nump)
{
pid_t pid;
int x = 0;
pid = fork();
if (pid < 0)
{
perror("There was an error during fork call: ");
exit(1);
}
//child Processes
if (pid == 0)
{
for (int i = 0; i < numOfProcs; i++)
{
printf("\nBEFORE Increment, ");
printf(" \nChild number: %d",i);
printf(" \nChild process ID: %d",(int) getpid());
printf(" \nCurrent value of num: %d", num);
printf(" \nCurrent value of nump: %d", *nump);
printf(" \nCurrent value of x: %d", x);
x += 5;
num ++;
(*nump)++;
printf("\nAFTER Increment, ");
printf(" \nChild number: %d",i);
printf(" \nChild process ID: %d",(int) getpid());
printf(" \nCurrent value of num: %d", num);
printf(" \nCurrent value of nump: %d", *nump);
printf(" \nCurrent value of x: %d", x);
}
exit(0);
}
//parent process
else
{
pid_t child;
while((child = wait(NULL)) != -1) {
printf("\nChild Process ended, Child PID: %d", (int)child);
}
}
return 0;
}
int main()
{
int nump = 100;
return concurrent(50, 2, &nump);
}