I am making the following code in C. I am writing a program that creates a new process using fork
system call. Then I want to check which one is active and finally if it's a child process return the list of all the directories within that file, or if it's a parent wait for termination of the child process.
Following is my code:
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <iostream>
int main(){
int pid = fork();
if(pid < 0){
printf(stderr, "Fork call failed! \n");
}
else if(pid == 0){
printf("This process is the child from fork=%d\n", pid);
printf("Thecurrent file inside the directory are:\n");
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
exit(0);
}
else{
printf("This process is the parent from fork=%d\n", pid);
int stats;
//parent process waits for child to terminate
waitpid(pid, &stats, 0);
if(stats == 0){
printf("This process is terminated.");
}
if(stats == 1){
printf("This process is terminated and an error has occured.");
}
}
return 0;
}
fatal error: iostream: No such file or directory #include <iostream>
^ compilation terminated.
If I remove #include <iostream>
, I get:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘struct _IO_FILE *’
how can I fix this problem?
Your error is in the first function call to printf()
:
printf(stderr, "Fork call failed! \n");
It should actually be fprintf()
instead:
fprintf(stderr, "Fork call failed! \n");
Also, don't forget to include:
unistd.h
for fork()
. sys/types.h
and sys/wait.h
for waitpid()
. stdlib.h
for exit()
. and remove #include <iostream>
since that is for C++.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.