Skip to content

Instantly share code, notes, and snippets.

@edvakf
Created March 17, 2010 03:05
Show Gist options
  • Save edvakf/334842 to your computer and use it in GitHub Desktop.
Save edvakf/334842 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define MAX_LINE_LEN 4096
#define MAX_ARGS_LEN 200
int chop(char *str)
{
const char c[] = "\0";
int len = strlen(str);
strcpy(str + len - 1, c);
return 0;
}
int split(char *str, char *words[], const char *delim)
{
int len;
char *cp;
cp = str;
for (len = 0; len < MAX_ARGS_LEN; len++) {
if ((words[len] = strtok(cp, delim)) == NULL)
break;
cp = NULL;
}
return 0;
}
int main(int argc, char *argv[])
{
pid_t pid;
char buf[MAX_LINE_LEN];
char *words[MAX_ARGS_LEN];
int i = 5;
while(i--) {
printf("> ");
fgets(buf, sizeof buf, stdin);
chop(buf);
if (strlen(buf) == 0) // just pressed return
continue;
split(buf, words, " "); // last element of words is NULL
pid = fork();
if (pid < 0) {
printf("fork(2) failed\n");
exit(1);
}
if (pid == 0) { // child process
execv(words[0], words);
perror(buf);
exit(99);
}
else { // parent process
waitpid(pid, NULL, 0);
}
}
printf("bye!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment