Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.0 kB
2
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/wait.h>


int main(int argc, char* argv[])
{
	char buf[1000];
	
	for(;;)
	{
		fputs("do?", stdout);
		fflush(stdout);
		fgets(buf, 1000, stdin);
		buf[strlen(buf)-1] = 0;
		if (0 == strcmp(buf, "leave"))
			break;
		else
		{
			if (!(fork())) // child code
			{
				char path[1000];
				char* curpath;
				strcpy(path, getenv("PATH"));
				
				for (curpath = strtok(path,":"); curpath != NULL; curpath = strtok(NULL, ":"))
				{
					int i = 0;
					char cmd[1000];
					char* argv[10];
					char* curargv;
					char* saveptr;

					for (curargv = strtok_r(cmd, "\t", &saveptr), i = 0; curargv!= NULL; curargv = strtok_r(NULL, "\t", &saveptr), i++)
					{
						argv[i] = curargv;
					}
					execv(cmd, argv);
					perror("exec");

				}

				execl("/bin/sh", "sh", "-c", buf, NULL);
				exit(-1);
			}
			else // parent
			{
				int status;
				wait(&status);
			}
		}
			
		
	}

	return 0;
}