#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[])
{
int i, max;
if (argc == 1)
max = 100;
else
max = atoi(argv[1]);
for (i=1; i<=max; i++) {
printf("%d\n", i);
sleep(1);
}
}
must terminate with 0. arg0 must be the executable name.
#include<stdio.h>
#include <unistd.h>
int main()
{
int ret=execl("./count", "count", "4", 0);
printf("ERROR !! exec returned: %d\n", ret);
}
as above, but
A[0] = arg0,
A[1] = arg1, ...
A[n] = 0.
#include<stdio.h>
#include <unistd.h>
int main()
{
char* A[3];
A[0] = "count";
A[1] = "4";
A[2] = 0;
/* here we pass an array of strings */
int ret = execv("./count",A);
printf("ERROR !! exec returned: %d\n", ret);
}
child process gets childpid == 0,
parent gets the child's process id
#include <stdio.h>
#include <unistd.h>
main()
{
int pchild,i;
pchild=fork();
if (pchild ==0) {
//I'm the child
int ret=execl("./count", "count", "4", 0);
printf("ERROR !! exec returned: %d\n", ret);
}
// I'm the parent
for(i=0;i<8;i++) {
printf("parent: %d\n", i);
sleep(1);
}
}
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
main()
{
int pchild,i;
int status;
pchild=fork();
if (pchild ==0) {
//I'm the child
int ret=execl("./count", "count", "4", 0);
printf("ERROR !! exec returned: %d\n", ret);
}
// I'm the parent
waitpid(pchild,&status,0);
for(i=0;i<8;i++) {
printf("parent: %d\n", i);
sleep(1);
}
}