Monday, 9 September 2013

execl("/bin/bash","bash","-l","-c","env",NULL), what's wrong?

execl("/bin/bash","bash","-l","-c","env",NULL), what's wrong?

I want to use execl("/bin/bash","bash","-l","-c","env",NULL) to get the
environment variables,the reason why I use parameter "-l" is that I
needn't source "/etc/profile","~/.bash_login" and so on. But when I run
it, the program is suspended and I have to use ctrl+c or ctrl+d to stop
it? Can you tell me how to modify it?
The code is shown as follows,getPtrArray is used to change one-dimensional
array to two-dimensional array.
int pid;
int fd[2];
char buffer[10000];
char** envi;
int res=pipe(fd);
//create a child process to get environment variable
if((pid=fork())==0){
close(fd[0]);
dup2(fd[1],STDOUT_FILENO);
struct passwd *pw=getpwnam("hgchen");
char *shell_type=pw->pw_shell;
if(execl("/bin/bash","bash","-l","-c","env",(char*)0)<0){
printf("Error\n");
}
exit(0);
}
// main process
else{
wait(NULL);
close(fd[1]);
int nbytes=read(fd[0],buffer,sizeof(buffer));
envi=getPtrArray(buffer);
}

No comments:

Post a Comment