I've a problem with exec() function under ubuntu. Is there any possibility to go back to the main program?
example:
printf("Some instructions at beginning\n");
execlp("ls","ls", "-l", NULL);
// i want to continue this program after exec and see the text below
printf("Other instructions\n");
The exec() functions return only if an error has occurred. The return value is -1, and errno is set to indicate the error.
What does exec return in Python? Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors. If there are no syntax errors, the parsed string is executed.
The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.
When a process calls exec, all code (text) and data in the process is lost and replaced with the executable of the new program. Although all data is replaced, all open file descriptors remains open after calling exec unless explicitly set to close-on-exec.
No. A successful exec
call replaces the current program with another program. If you want both the parent and child to stick around, you need to call fork(2)
before exec
:
pid_t childpid = fork();
if(childpid < 0)
{
// Handle error
}
else if(childpid == 0)
{
// We are the child
exec(...);
}
else
{
// We are the parent: interact with the child, wait for it, etc.
}
Note that a failed exec
call (e.g. the given executable doesn't exist) does return. If exec
returns, it's always because of an error, so be prepared to handle the error.
exec
replaces the executable file image. There is no way back. A nice alternative is vfork() exec
. vfork
copies the process, continues in the copy and when it completes its execution, continues the main process. The copy can exec
the desired file. Example:
printf("Some instructions at beginning\n");
if(!vfork()){
// child
execlp("ls","ls", "-l", NULL); // child is replaced
}
// parent continues after child is gone
printf("Other instructions\n");
No, Not possible using exec family functions because the executable file, which is generated from your previous code i.e. code which contains execlp("ls","ls","-l",NULL) function, is replaced by the executable file you are going to run by execlp() function i.e. ls. So when this function is executed successfully, you no more have that old executable file containing execlp() function.
Use system("ls -l"); function if you want to run any other process and want to return to current process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With