[英]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.