Last active
September 5, 2018 16:03
-
-
Save giuliano-macedo/27312d6447f738f40a8058210eb5b966 to your computer and use it in GitHub Desktop.
Get ping realtime stdout and exit code in C using forkpty and execvp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <pty.h> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
int ptytest(){ | |
int master; | |
pid_t pid; | |
pid = forkpty(&master, NULL, NULL, NULL); | |
if(pid<0)return 1; | |
else if (pid == 0){ | |
char* args[]={"bash","-c","ping -c 5 8.8.8.8",NULL}; | |
execvp("/bin/bash",args); | |
} | |
else{ | |
FILE* fp=fdopen(master, "r"); | |
char line[256]; | |
while(fgets(line,256,fp)){ | |
printf("[PING] %s",line); | |
} | |
int status; | |
waitpid(pid, &status, 0); | |
fclose(fp); | |
return WEXITSTATUS(status); | |
} | |
return 0; | |
} | |
int main(){ | |
int ret=ptytest(); | |
printf("exit code: %i\n",ret); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment