I want to run bash as child process of my C program.
Few conditions
1) My program will handle both STDIN and STDOUT of bash.
2) No care about practical use.
I have done it but it does not looks like bash.
Here is my code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/wait.h>
// for tunneling the data
struct tnl {
int in;
int out;
};
// for tunneling the data
void *do_tnl(void *ptr);
int main(int argc,char **argv) {
int p1[2];
int p2[2];
pipe(p1);
pipe(p2);
int c_pid = fork();
if (c_pid == 0) {
// child
dup2(p1[0], 0);
close(p1[1]);
dup2(p2[1], 1);
close(p2[0]);
char *argv1[2];
argv1[0]=argv[1];
argv1[1]=NULL;
execvp(argv[1], argv1);
} else {
// parent
close(p1[0]);
close(p2[1]);
struct tnl t1;
t1.in = 0;
t1.out = p1[1];
struct tnl t2;
t2.in = p2[0];
t2.out = 1;
pthread_t thread1, thread2;
int iret1, iret2;
iret1 = pthread_create(&thread1, NULL, do_tnl, (void*) &t1);
iret2 = pthread_create(&thread2, NULL, do_tnl, (void*) &t2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Thread 1 returns: %d\n", iret1);
printf("Thread 2 returns: %d\n", iret2);
int st;
wait(&st);
}
return 0;
}
void *do_tnl(void *ptr) {
struct tnl *t = ptr;
while (1) {
int buf[1];
int r = read(t->in, buf, 1);
if (r > 0) {
write(t->out, buf, 1);
} else {
break;
}
}
}
// Run example
[u123@Sohani ~]$ ./myprog /bin/bash
pwd
/home/u123
who
u123 :0 2013-01-16 03:31 (:0)
u123 pts/0 2013-01-18 23:23 (:0)
u123 pts/1 2013-01-19 03:04 (:0)
u123 pts/3 2013-01-19 02:31 (:0)
exit
[u123@Sohani ~]$
// Run example end
So as you can see that it is working. I can now run any command(e.g. here I tun pwd, who, exit). But the problem is that
1) The output is not color full.
2) There is no "[u123@Sohani ~]$" part in bash.
So I want the same effect as it happen when I run bash normally in terminal.
I am sure that it is possible because I can run a ssh-server(sshd) and ssh-client(ssh) with normal privilege and there I have bash running like it run normally.
I have searched on net. And openssh code is too large.
I am using Fedora 17 64 bit.
So please help.
Thanks in advance.