EverEffects Backup Forum
Welcome To We Can't Program Forums, Please Log In To Access All Forums.

Enjoy Your Stay

- Staff
EverEffects Backup Forum
Welcome To We Can't Program Forums, Please Log In To Access All Forums.

Enjoy Your Stay

- Staff
EverEffects Backup Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

EverEffects Backup Forum

Designers World
 
HomePortalLatest imagesRegisterLog in



 Basic Shell [C++] Resize


Share | 
 

 Basic Shell [C++]

View previous topic View next topic Go down 
AuthorMessage
Fred
Staff
Staff
Fred

Posts : 33
Join date : 2010-05-27
Age : 31
Location : Oklahoma

Basic Shell [C++] _
PostSubject: Basic Shell [C++]   Basic Shell [C++] EmptyThu Jun 03, 2010 2:43 pm
Something my father showed me awhile back, quite a good resource if you want to program a computer.

Code:

#include <iostream>
#include <unistd.h>

int
main()
{
int rv = system("ls -l ~/");
std::cout << "result code: " << rv << "\n";
return 0;
}


Here's an example of doing it the hard way.

#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int
main()
{
int kidstatus, deadpid;

pid_t kidpid = fork();
if (kidpid == -1) {
std::cerr << "fork error " << errno << ", "
<< std::strerror(errno) << "\n";
return 1;
}
if (kidpid == 0) {
// okay, we're the child process. Let's transfer control
// to the ls program. "ls" in both of the spots in the list
// is not a mistake! Only the second argument on are argv.
// note the NULL at the end of the list, you need that.
#if 0
// this version uses the shell.
int rv = execlp("/bin/sh", "/bin/sh", "-c", "ls -l /var/log", NULL);
#else
// this version runs /bin/ls directly.
int rv = execlp("/bin/ls", "/bin/ls", "-l", "/var/log/", NULL);
#endif
// if the execlp is successful we never get here:
if (rv == -1) {
std::cerr << "execlp error " << errno << ", "
<< std::strerror(errno) << "\n";
return 99;
}
return 0;
}
// we only get here if we're the parent process.
deadpid = waitpid(kidpid, &kidstatus, 0);
if (deadpid == -1) {
std::cerr << "waitpid error " << errno << ", "
<< std::strerror(errno) << "\n";
return 1;
}
std::cout << "child result code: " << WEXITSTATUS(kidstatus)
<< "\n";
return 0;
}

Credit: d4rk_bunneh
Back to top Go down
http://wcpforums.friendhood.net
 

Basic Shell [C++]

View previous topic View next topic Back to top 
Page 1 of 1

Permissions in this forum:You cannot reply to topics in this forum
EverEffects Backup Forum :: C/C++/C#/VisualC++-
Jump to:  


   [Valid RSS]





Free forum | ©phpBB | Free forum support | Report an abuse | Forumotion.com