How to rerun the program in C language?
In C language, the program can be re-executed by calling the exec() function. The exec() function is a system call function that replaces the current process with a new process. When calling the exec() function, you can specify the program path and command line arguments to be executed. Here is a simple example code:
#include <stdio.h>
#include <unistd.h>
int main() {
printf("I am the original program\n");
char *args[] = {"./new_program", NULL};
execvp(args[0], args);
printf("This line will not be printed because the program has been replaced\n");
return 0;
}
In the code above, we start by printing a message, followed by defining a string array called args to store the path of the new program to be executed. We then call the execvp() function to replace the current process with the new program new_program. If the execvp() function successfully executes, the rest of the original program’s code will not be run.
It is important to note that functions in the exec() family will replace the current process with a new program, causing the original program’s state and data to be lost. If you want to run a program again after the original process ends, consider using a combination of fork() and exec() – first create a child process, then call exec() in the child process to execute the new program.