So we had our first touch with system(), fork(), execvp(), and wait() .
I can not distinguish the difference between system() and execvp() :/
So let give two pieces of code that use them and produce similar output
execvp
Code:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
char program[80],*args[3];
int i;
printf("Ready to exec()...\n");
strcpy(program,"date");
args[0]="date";
args[1]="-u";
args[2]=NULL;
i=execvp(program,args);
printf("i=%d did not work!\n",i);
return 0;
}
outputs
Code:
Macintosh-c8bcc88e5669-9:~ usi$ ./bla
Ready to exec()...
Thu Nov 22 11:51:31 UTC 2012
Macintosh-c8bcc88e5669-9:~ usi$
system
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
char text[80];
printf("Ready to system()...\n");
sprintf(text,"date -u");
system(text);
printf("Line after system call.\n");
return 0;
}
output
Code:
Macintosh-c8bcc88e5669-9:~ usi$ ./px
Ready to system()...
Thu Nov 22 11:52:58 UTC 2012
Line after system call.
Macintosh-c8bcc88e5669-9:~ usi$
The difference I spotted is that with execvp , it will not go to the next line of code..So what happens?
I read the documentation and said that it will open a new image (something like that) ..
But it is not at clear to me.What is the effect of the function?system will output the same result of date but then it will go to the next line of code....Why?
Maybe something with wait function happens internally of system....?
I can say that system actually may call internally fork, wait and execvp because our homework is to write a function that behaves equivalently to system and the skeleton is this
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
void fork_snippet() {
int i;
if ((i=fork()) == 0) { // child code
} else { // parent code
assert(i!=-1);
}
}
void wait_snippet() {
int cpid=wait(NULL);
assert(cpip!=-1);
}
void exec_snippet() {
char *args[] = {"date","-u",NULL};
assert(execvp(args[0],args)!=-1);
}
void strsep_snippet() {
char *token, *string, *tofree;
tofree = string = strdup("abc,def,ghi");
assert(string != NULL);
while ((token = strsep(&string, ",")) != NULL)
printf("%s\n", token);
free(tofree);
}
Every input is precious . I have 0 experience with system calls so if you want to write a big explanation do not hesitate to do so
Tip : Remember, if someone has good knowledge of something, he can explain it in a simple way..