[Dev-C++] Re: Re: execution of a string with system()
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Christophe C. <chr...@fr...> - 2002-09-19 14:12:46
|
This sample (chunck only) try to copy a file using 'cp' command, and is
thread-safe.
At my knowledge, should run on any Un*x system.
The idea is :
- create a second process using fork() - this function copy the
current process in a new one. Both processes are then continued from this
point. In the parent process, the return value is the child PID, in the
child it is 0.
- in the parent process, wait for termination of the child process
(using waitpid()), to synchronize both processes like with a system() call.
- in the child process, create the command line (command +
parameters) to be executed, and use execve() (or other exec* function) to
replace itself (the code of current process) by the command's code.
#include <unistd.h> /* For fork() and execvp() */
#include <sys/types.h> /* For pid_t */
#include <sys/wait.h> /* For waitpid() */
pid_t PID; /* The child PID */
int RC=0; /* The command return code */
...
...
...
PID=fork(); /* Create a new process */
if (PID) /* Executed when in the parent process, PID !
= 0 */
{
waitpid(PID,&RC,0); /* Wait for termination of the child process
and get its return code */
if (RC>>8) /* Test the return code - many values can be
tested - here, I test only wether it is 0 or not */
{
fprintf(stderr,"Error copying file - cp return code [%d]\n",RC>>8);
exit(EXIT_FAILURE);
}
else
printf"File copied !\n");
}
else /* Executed when in the child process, PID == 0 */
{
char **SysParams=new char *[4]; /* This array will contain the
name of the command, with parameters, terminated by a NULL pointer. This
will be the argv[] array of the called command */
SysParams[0]="cp"; /* Command */
SysParams[1]=InFileName; /* First param - must be a char *
*/
SysParams[2]=OutFileName; /* Second param - must be a char
* */
SysParams[3]=NULL; /* Terminator */
if (execvp(SysParams[0],SysParams)==-1) /* Replace itself with the
SysParams[0] program, called with SysParams as argv[]
Once exexvp() is started, the
original process is destroyed - it never continues after that point. The
only exception is if execvp() fails (for example if the command can't be
executed).
In this case, we process the
error... I think there are some methods to have a "nice" description of the
error (maybe perror() with errno ?) but I don't know them. */
{
fprintf(stderr,"Error in execvp for copying file !\n");
exit(EXIT_FAILURE);
}
}
...
...
Good luck in multi-threaded programming !
Christophe
|