[英]Functions not running concurrently in C
我正在尝试使用 fork() 使两个 function 在 C 中同时运行,由于某种原因,c1 似乎执行了两次,而 c2 永远不会被执行。 这是代码:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
void c1();
void c2(char *argv[]);
int wait_rv; /* return value from wait() */
int child_status;
int pid1,pid2,pid3,parentPID;
parentPID = getpid();
if((pid1 = fork()) == -1)
{
fprintf(stderr, "Cannot fork child1 \n");
}else{
c1();
exit(17);
}
if((pid2 = fork()) == -1)
{
fprintf(stderr, "Cannot fork child 2\n");
}else{
c2(argv);
exit(17);
}
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("Please provide the file path as command line argument\n");
}
c2(argv);
}
void c1()
{
int counter = 0;
float grades[10];
float result = 0;
printf("child %d here. Will calculate average marks.\n", getpid());
printf("Please enter 10 marks: \n");
do{
printf("(%d)",counter+1);
scanf("%f",&grades[counter]);
counter++;
}while(counter < 10);
for(counter;counter>=0;counter--){
result = result + grades[counter];
}
printf("Average: %f",result/10);
}
void c2(char *argv[] ){
FILE *fptr;
char ch;
int wrd=1,charctr=1;
printf("child %d here. Will execute wc\n", getpid());
fptr=fopen(argv[1],"r");
if(fptr==NULL)
{
printf(" File does not exist or can not be opened.");
perror(fptr);
}
else
{
ch=fgetc(fptr);
while(ch!=EOF)
{
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
charctr++;
}
ch=fgetc(fptr);
}
printf("\n The number of words in the file %s are : %d\n",argv[1],wrd-2);
}
fclose(fptr);
}
这是我的 output:
child 27931 here. Will calculate average marks.
Please enter 10 marks:
(1)child 27932 here. Will calculate average marks.
Please enter 10 marks:
(1)1
(2)2
(3)3
(4)4
(5)5
(6)6
(7)7
(8)8
(9)9
(10)10
(2)1
Average: 4.600000-bash-4.1$
由于某种原因,它变得一团糟,并试图在最后获得一个额外的分数。
你需要做这样的事情:
int pid = fork();
// Check if forking failed
if(pid == -1) exit(1);
// If we are in child, run c1
else if(pid == 0) {
// Code here will ONLY be run by child
c1(argv);
}
// If we are in parent, run c0
else {
// Code here will ONLY be run by parent
c0();
}
// Anything that comes after here will be run by BOTH processes
// unless they exit first
您需要在这里了解的是,在调用 fork 之后(除非它失败),您有两个进程正在运行。 对于它们中的每一个,您可以通过检查pid
的值来找出它是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.