- Joined
- Jul 9, 2008
- Messages
- 1
- Reaction score
- 0
Hi,
I am trying to create an interactive shell inside a C program.
I call popen to get a file pointer which also invokes a shell. I pass a command to that and then use fgets to get the reply back from the shell. I leave the pointer open for a subsequent command. When I want to do another command I use fputs to send it the command line, but I get an error code of 5 back when I do so. Any further interaction with the file pointer yields a SIGPIPE.
Code is below.
Can anyone tell me what the proper way is to, in C, create a shell and issue multiple commands and receive output from those?
Thanks!
- (char*)doShellchar*) cmd
{
int resultCode = 0;
char* rValue;
char* dataR = (char*)malloc(cCMDReturnBufSize);
char* dataOff = dataR;
if (dataR == NULL)
dataR = (char*)malloc(cCMDReturnBufSize);
if (fp == NULL)
fp = popen(cmd, "r+");
else
{
resultCode = fputs(cmd, fp);
}
fprintf("result code %i\n", resultCode);
// Should REALLY check the output for error.
do
{
rValue = fgets(dataOff, cCMDReturnBufSize, fp);
if (rValue != NULL)
{
dataOff += strlen(rValue);
}
} while ((rValue != NULL) && ((dataOff-dataR) < cCMDReturnBufSize)); // Proceed as long as there is more data, or our buffer is full
return dataR;
}
I am trying to create an interactive shell inside a C program.
I call popen to get a file pointer which also invokes a shell. I pass a command to that and then use fgets to get the reply back from the shell. I leave the pointer open for a subsequent command. When I want to do another command I use fputs to send it the command line, but I get an error code of 5 back when I do so. Any further interaction with the file pointer yields a SIGPIPE.
Code is below.
Can anyone tell me what the proper way is to, in C, create a shell and issue multiple commands and receive output from those?
Thanks!
- (char*)doShellchar*) cmd
{
int resultCode = 0;
char* rValue;
char* dataR = (char*)malloc(cCMDReturnBufSize);
char* dataOff = dataR;
if (dataR == NULL)
dataR = (char*)malloc(cCMDReturnBufSize);
if (fp == NULL)
fp = popen(cmd, "r+");
else
{
resultCode = fputs(cmd, fp);
}
fprintf("result code %i\n", resultCode);
// Should REALLY check the output for error.
do
{
rValue = fgets(dataOff, cCMDReturnBufSize, fp);
if (rValue != NULL)
{
dataOff += strlen(rValue);
}
} while ((rValue != NULL) && ((dataOff-dataR) < cCMDReturnBufSize)); // Proceed as long as there is more data, or our buffer is full
return dataR;
}