![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: May 2005
Posts: 1
Rep Power: 0
![]() |
I'm almost new to socket programming, but I need to write a simple remote shell running under freebsd for a university exam.
The client-server connection is working seamlessly (PF_INET protocol). I've got troubles figuring out how to send back to the client the standard output & error. Some people suggested me to make the server execute the command and redirect its stdout and stderr to files with this call: system( "(command_string > stdout) 2> stderr" ); That solution seems to me very rough and shell-dependent (not working on csh for example). Which are the other more elegant methods of doing it? Thanks in advance, G.B. |
|
|
|
|
|
#2 |
|
PFO God In Training
![]() Join Date: Jun 2005
Location: near St Louis, MO. (USA)
Posts: 652
Rep Power: 4
![]() |
instead of using system() function, duplicate stdout and stderr, then spawn the program with one of the spawn family of functions. This function redirects stderr and stdout to a file. It was written for MS-Windows, but I think it is nearly identical to the way *nix implements it.
void CreateFiles(string basename)
{
string filename;
// create a file for stdout and stderr
filename = basename + ".txt";
int fd = open(filename.c_str(), _O_CREAT | _O_TRUNC | _O_WRONLY | _O_TEXT,_S_IREAD | _S_IWRITE);
if(fd < 0)
{
cout << "Error opening file: " << filename << endl;
exit(1);
}
if((-1 == dup2(fd,1)) || (-1 == dup2(fd,2)))
{
cout << "Error duping stderr and stdout." << endl;
exit(1);
}
//
// call _spawn() here to execute the shell command
close(fd); // close the file
} |
|
|
|
|
|
#3 |
|
Programmer
Join Date: May 2005
Location: England
Posts: 61
Rep Power: 4
![]() |
Surely you could use popen()? It'd probably reduce the amount of code required to do the task. Just man popen for more information on how it works.
With a more hacked idea, I suppose you could fork() and pipe the output of your command to a named pipe, and route stdin from another named pipe. Then you could easily gain access to stdin, stdout and stderr from the program by use of file descriptors. This idea doesn't seem very elegant though. I think there must be a more elegant, or prebuilt way, to do this.
__________________
http://www.nuticulus.net/hackmysig/sig.PNG Give my site a chance, you know you want to ;-) Google will solve 99% of your problems. Including those with your sex life. Caution, may <strike>contain</strike> be nuts. Last edited by Nuticulus; Jun 6th, 2005 at 3:35 PM. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|