How to use fork () and exec () correctly

I have this code;

pid_t process; process = fork(); if (process < 0){ //fork error perror("fork"); exit(EXIT_FAILURE); } if (process == 0){ //i try here the execl execl ("process.c", "process" , n, NULL); } else { wait(NULL); } 

I don't know if fork() and exec() are used correctly. When I try to run the program from bash, I do not get any result, so I thought this might be a problem in this part of the code.
Thanks.

+4
source share
2 answers

One of the problems is that

 if (process = 0){ 

must read

 if (process == 0){ 

Otherwise, you assign zero to process and only execl if result is nonzero (i.e. never).

In addition, you are trying to execute something called process.c . There is no doubt that it may have an executable process.c file. However, conditional names ending in .c are passed to the C source files. If process.c really a C file, you need to compile it and link it first.

Once you have created the executable, you need to either place it somewhere on $PATH or indicate its full path to execle() . In many Unix environments, placing it in the current directory will not be enough.

Finally, it is unclear that n is in the call to execle() , but the name alludes to a numerical variable. You must make sure that it is a string, and not, for example, an integer.

+15
source

According to the answers and comments above, your code should look something like this:

 pid_t process; process = vfork(); //if your sole aim lies in creating a child that will ultimately call exec family functions then its advisable to use vfork if (process < 0) { //fork error perror("fork"); exit(EXIT_FAILURE); } if (process == 0) { //i try here the execl char N[MAX_DIGITS];//A correction here itoa(n,N);//write this function yourself execl ("process", "process" , N, NULL);// Here process is the name of the executable N is your original argument fprintf(stderr,"execl failed\n");//check for error in execl } else { wait(NULL); } 

Pay attention to using vfork instead of fork.Its, because it will be much more efficient. The reason can be found here.

-1
source

Source: https://habr.com/ru/post/1384509/


All Articles