C program to implement the system function

When a process calls one of the exec functions, that process is completely replaced by the new program, and the new program starts executing at its main function. The process ID does not change across an exec, because a new process is not created; exec merely replaces the current process – its text, data, heap, and stack segments – with a brand new program from disk.

There are six exec functions:
#include<unistd.h>
int execl(const char *pathname, const char *arg0,… /* (char *)0 */ );
int execv(const char *pathname, char *const argv [ ]);
int execle(const char *pathname, const char *arg0,… /*(char *)0, char *const envp */ );
int execve(const char *pathname, char *const argv[ ], char *const envp[]);
int execlp(const char *filename, const char *arg0, … /* (char *)0 */ );
int execvp(const char *filename, char *const argv [ ]);

				
					#include<sys/wait.h>
#include<errno.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int system(const char *cmdstring)
{
pid_t pid;
int status;
if (cmdstring == NULL)
return(1);
if ((pid = fork()) < 0)
{
status = -1;
}
else if (pid == 0)
{
/* child */
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
_exit(127); /* execl error */
}
else
/* parent */
while (waitpid(pid, &status, 0) < 0)
{
if (errno != EINTR)
status = -1; /* error other than EINTR from waitpid() */
break;
}
return(status);
}
int main()
{
int status;
if ((status = system("date")) < 0)
printf("system() error");
if ((status = system("who")) < 0)
printf("system() error");
exit(0);
}
				
			
Output:
Mon June 1 18:03:31 IST 2019
root pts/1 2018-04-01 17:38 (:0.0)

Leave a Reply