コード例 #1
0
status_t CommandSection::Execute(ReportRequestSet* requests) const {
    FdBuffer buffer;
    Fpipe cmdPipe;
    Fpipe ihPipe;

    if (!cmdPipe.init() || !ihPipe.init()) {
        ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
        return -errno;
    }

    pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
    if (cmdPid == -1) {
        ALOGW("CommandSection '%s' failed to fork", this->name.string());
        return -errno;
    }
    pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
    if (ihPid == -1) {
        ALOGW("CommandSection '%s' failed to fork", this->name.string());
        return -errno;
    }

    cmdPipe.writeFd().reset();
    status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
    write_section_stats(requests->sectionStats(this->id), buffer);
    if (readStatus != NO_ERROR || buffer.timedOut()) {
        ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
              this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
        kill_child(cmdPid);
        kill_child(ihPid);
        return readStatus;
    }

    // Waiting for command here has one trade-off: the failed status of command won't be detected
    // until buffer timeout, but it has advatage on starting the data stream earlier.
    status_t cmdStatus = wait_child(cmdPid);
    status_t ihStatus = wait_child(ihPid);
    if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
        ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident "
              "helper: %s",
              this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
        return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
    }

    VLOG("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
         (int)buffer.durationMs());
    status_t err = write_report_requests(this->id, buffer, requests);
    if (err != NO_ERROR) {
        ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
        return err;
    }
    return NO_ERROR;
}
コード例 #2
0
ファイル: main.c プロジェクト: sunwxg/monitor_ssh
void parent_process(pid_t pid)
{
	FILE *fp;
	int interval = FAIL_CHECK_INTERNAL;

	print_log("main process: pid=%d", getpid());

	if (signal(SIGTERM, sig_term) == SIG_ERR)
		print_log("can't register SIGTERM");

	while (1) {
		sleep(interval);

		int res = check_status();
		if (res != 0) {
			fp = fopen(tmp_file, "r");
			if (fp != NULL) {
				kill_child(fp);
				fclose(fp);
				interval = FAIL_CHECK_INTERNAL;
				break;
			}
			print_log("error open %s", tmp_file);
			interval = FAIL_CHECK_INTERNAL;
			break;
		}
		interval = CHECK_INTERNAL;
	}

	remove(tmp_file);
}
コード例 #3
0
status_t FileSection::Execute(ReportRequestSet* requests) const {
    // read from mFilename first, make sure the file is available
    // add O_CLOEXEC to make sure it is closed when exec incident helper
    unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
    if (fd.get() == -1) {
        ALOGW("FileSection '%s' failed to open file", this->name.string());
        return this->deviceSpecific ? NO_ERROR : -errno;
    }

    FdBuffer buffer;
    Fpipe p2cPipe;
    Fpipe c2pPipe;
    // initiate pipes to pass data to/from incident_helper
    if (!p2cPipe.init() || !c2pPipe.init()) {
        ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
        return -errno;
    }

    pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
    if (pid == -1) {
        ALOGW("FileSection '%s' failed to fork", this->name.string());
        return -errno;
    }

    // parent process
    status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
                                                           std::move(c2pPipe.readFd()),
                                                           this->timeoutMs, mIsSysfs);
    write_section_stats(requests->sectionStats(this->id), buffer);
    if (readStatus != NO_ERROR || buffer.timedOut()) {
        ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
              this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
        kill_child(pid);
        return readStatus;
    }

    status_t ihStatus = wait_child(pid);
    if (ihStatus != NO_ERROR) {
        ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(),
              strerror(-ihStatus));
        return ihStatus;
    }

    VLOG("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
         (int)buffer.durationMs());
    status_t err = write_report_requests(this->id, buffer, requests);
    if (err != NO_ERROR) {
        ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
        return err;
    }

    return NO_ERROR;
}
コード例 #4
0
status_t wait_child(pid_t pid) {
    int status;
    bool died = false;
    // wait for child to report status up to 1 seconds
    for (int loop = 0; !died && loop < WAIT_MAX; loop++) {
        if (waitpid(pid, &status, WNOHANG) == pid) died = true;
        // sleep for 0.2 second
        nanosleep(&WAIT_INTERVAL_NS, NULL);
    }
    if (!died) return kill_child(pid);
    return statusCode(status);
}
コード例 #5
0
ファイル: server_child.c プロジェクト: Distrotech/netatalk
/* if the times don't match mac has been rebooted */
void server_child_kill_one_by_id(server_child_t *children, pid_t pid,
                                 uid_t uid, uint32_t idlen, char *id, uint32_t boottime)
{
    afp_child_t *child, *tmp;
    int i;

    pthread_mutex_lock(&children->servch_lock);
    
    for (i = 0; i < CHILD_HASHSIZE; i++) {
        child = children->servch_table[i];
        while (child) {
            tmp = child->afpch_next;
            if (child->afpch_pid != pid) {
                if (child->afpch_idlen == idlen && memcmp(child->afpch_clientid, id, idlen) == 0) {
                    if ( child->afpch_boottime != boottime ) {
                        /* Client rebooted */
                        if (uid == child->afpch_uid) {
                            kill_child(child);
                            LOG(log_warning, logtype_default,
                                "Terminated disconnected child[%u], client rebooted.",
                                child->afpch_pid);
                        } else {
                            LOG(log_warning, logtype_default,
                                "Session with different pid[%u]", child->afpch_pid);
                        }
                    } else {
                        /* One client with multiple sessions */
                        LOG(log_debug, logtype_default,
                            "Found another session[%u] for client[%u]", child->afpch_pid, pid);
                    }
                }
            } else {
                /* update childs own slot */
                child->afpch_boottime = boottime;
                if (child->afpch_clientid)
                    free(child->afpch_clientid);
                LOG(log_debug, logtype_default, "Setting client ID for %u", child->afpch_pid);
                child->afpch_uid = uid;
                child->afpch_valid = 1;
                child->afpch_idlen = idlen;
                child->afpch_clientid = id;
            }
            child = tmp;
        }
    }

    pthread_mutex_unlock(&children->servch_lock);
}
コード例 #6
0
ファイル: server_child.c プロジェクト: xrmx/Netatalk
/* if the times don't match mac has been rebooted */
void server_child_kill_one_by_id(server_child *children, int forkid, pid_t pid,
                                 uid_t uid, uint32_t idlen, char *id, uint32_t boottime)
{
    server_child_fork *fork;
    struct server_child_data *child, *tmp;
    int i;

    fork = (server_child_fork *)children->fork + forkid;

    for (i = 0; i < CHILD_HASHSIZE; i++) {
        child = fork->table[i];
        while (child) {
            tmp = child->next;
            if ( child->pid != pid) {
                if (child->idlen == idlen && memcmp(child->clientid, id, idlen) == 0) {
                    if ( child->time != boottime ) {
                        /* Client rebooted */
                        if (uid == child->uid) {
                            kill_child(child);
                            LOG(log_warning, logtype_default,
                                "Terminated disconnected child[%u], client rebooted.",
                                child->pid);
                        } else {
                            LOG(log_warning, logtype_default,
                                "Session with different pid[%u]", child->pid);
                        }
                    } else {
                        /* One client with multiple sessions */
                        LOG(log_debug, logtype_default,
                            "Found another session[%u] for client[%u]", child->pid, pid);
                    }
                }
            } else {
                /* update childs own slot */
                child->time = boottime;
                if (child->clientid)
                    free(child->clientid);
                LOG(log_debug, logtype_default, "Setting client ID for %u", child->pid);
                child->uid = uid;
                child->valid = 1;
                child->idlen = idlen;
                child->clientid = id;
            }
            child = tmp;
        }
    }
}
コード例 #7
0
ファイル: rename-under-feet.c プロジェクト: adeason/openafs
int
main(int argc, char **argv)
{
    struct stat sb;
    int ret;
    int fd;
    char buf[1];
    int status;


    emkdir("one", 0777);
    emkdir("two", 0777);
    emkdir("one/a", 0777);

    fd = child_chdir("one/a");
    atexit(kill_child);
    ret = read(fd, buf, 1);
    if (ret < 0)
	err(1, "read");
    if (ret == 0)
	errx(1, "EOF on read");

    ret = rename("one/a", "two/a");
    if (ret < 0)
	err(1, "rename one/a two");
    ret = lstat("two/a", &sb);
    if (ret < 0)
	err(1, "lstat two/a");
    ret = lstat("one/a", &sb);
    if (ret != -1 || errno != ENOENT)
	errx(1, "one/a still exists");
    kill_child();
    waitpid(child_pid, &status, 0);
    ret = lstat("one/a", &sb);
    if (ret != -1 || errno != ENOENT)
	errx(1, "one/a still exists after child");
    if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
	rmdir("one/a");
	rmdir("two/a");
	rmdir("one");
	rmdir("two");
	return 0;
    } else
	return 1;
}
コード例 #8
0
ファイル: irchandler.c プロジェクト: knusbaum/KIRC
void broadcast(struct message *m, fd_set *writefds) {
    struct handler *h = handlers;
    while(h) {
        if(h->h_type == PERSISTENT) {
            char *buff;
            switch(h->i_type) {
            case JSON:
                buff = message_to_json(m);
                if(! (ensure_write(h->fdout, buff, strlen(buff))
                      && ensure_write(h->fdout, "\n", 1))) {
                    fprintf(stderr, "Failed to write to handler %s\n", h->command);
                }
                break;

            case RAW:
                buff = message_to_IRC(m);
                break;
            }
        }
        else if(h->h_type == TRANSIENT) {
            kill_child(h);
            launch_child(h);
            char *buff;
            switch(h->i_type) {
            case JSON:
                buff = message_to_json(m);
                if(! (ensure_write(h->fdout, buff, strlen(buff))
                      && ensure_write(h->fdout, "\n", 1))) {
                    fprintf(stderr, "Failed to write to handler %s\n", h->command);
                }
                close(h->fdout);
                break;
            case RAW:
                buff = message_to_IRC(m);
                if( ! ensure_write(h->fdout, buff, strlen(buff))) {
                    fprintf(stderr, "Failed to write to handler %s\n", h->command);
                }
                close(h->fdout);
                break;
            }
        }
        h = h->next;
    }
}
コード例 #9
0
ファイル: run4.c プロジェクト: jazzyb/run4
int
main (int argc, char *argv[])
{
    int i;
    int time;
    char *args[ARG_MAX+1];

    if (argc != 4) {
        usage();
        if (argc == 2 && strcmp(argv[1], "-h") == 0) {
            exit(0);
        } else {
            exit(1);
        }
    }

    time = convert_to_seconds(argv[1], argv[2]);
    convert_to_argument_list(args, argv[3]);

    cpid = fork();
    if (cpid == 0) {
        execvp(args[0], args);
        // if execvp() returns, then something failed:
        fprintf(stderr, "error: unable to exec the command\n");
        exit(1);

    } else if (cpid > 0) {
        signal(SIGINT, sighandler);
        signal(SIGTERM, sighandler);
        sleep(time);
        kill_child();

    } else {
        fprintf(stderr, "error: unable to fork\n");
        exit(1);
    }

    return 0;
}
コード例 #10
0
ファイル: main.c プロジェクト: freexploit/i3wm
int main(int argc, char **argv) {
    int opt;
    int option_index = 0;
    char *socket_path = getenv("I3SOCK");
    char *command = NULL;
    char *fontname = NULL;
    char *i3_default_sock_path = "/tmp/i3-ipc.sock";
    struct xcb_color_strings_t colors = { NULL, };

    /* Definition of the standard-config */
    config.hide_on_modifier = 0;
    config.dockpos = DOCKPOS_NONE;
    config.disable_ws = 0;

    static struct option long_opt[] = {
        { "socket",               required_argument, 0, 's' },
        { "command",              required_argument, 0, 'c' },
        { "hide",                 no_argument,       0, 'm' },
        { "dock",                 optional_argument, 0, 'd' },
        { "font",                 required_argument, 0, 'f' },
        { "nows",                 no_argument,       0, 'w' },
        { "help",                 no_argument,       0, 'h' },
        { "version",              no_argument,       0, 'v' },
        { "verbose",              no_argument,       0, 'V' },
        { "color-bar-fg",         required_argument, 0, 'A' },
        { "color-bar-bg",         required_argument, 0, 'B' },
        { "color-active-ws-fg",   required_argument, 0, 'C' },
        { "color-active-ws-bg",   required_argument, 0, 'D' },
        { "color-inactive-ws-fg", required_argument, 0, 'E' },
        { "color-inactive-ws-bg", required_argument, 0, 'F' },
        { "color-urgent-ws-bg",   required_argument, 0, 'G' },
        { "color-urgent-ws-fg",   required_argument, 0, 'H' },
        { "color-focus-ws-bg",    required_argument, 0, 'I' },
        { "color-focus-ws-fg",    required_argument, 0, 'J' },
        { NULL,                   0,                 0, 0}
    };

    while ((opt = getopt_long(argc, argv, "s:c:d::mf:whvVA:B:C:D:E:F:G:H:I:J:", long_opt, &option_index)) != -1) {
        switch (opt) {
            case 's':
                socket_path = expand_path(optarg);
                break;
            case 'c':
                command = strdup(optarg);
                break;
            case 'm':
                config.hide_on_modifier = 1;
                break;
            case 'd':
                config.hide_on_modifier = 0;
                if (optarg == NULL) {
                    config.dockpos = DOCKPOS_BOT;
                    break;
                }
                if (!strcmp(optarg, "top")) {
                    config.dockpos = DOCKPOS_TOP;
                } else if (!strcmp(optarg, "bottom")) {
                    config.dockpos = DOCKPOS_BOT;
                } else {
                    print_usage(argv[0]);
                    exit(EXIT_FAILURE);
                }
                break;
            case 'f':
                fontname = strdup(optarg);
                break;
            case 'w':
                config.disable_ws = 1;
                break;
            case 'v':
                printf("i3bar version " I3_VERSION " © 2010-2011 Axel Wagner and contributors\n");
                exit(EXIT_SUCCESS);
                break;
            case 'V':
                config.verbose = 1;
                break;
            case 'A':
                read_color(&colors.bar_fg);
                break;
            case 'B':
                read_color(&colors.bar_bg);
                break;
            case 'C':
                read_color(&colors.active_ws_fg);
                break;
            case 'D':
                read_color(&colors.active_ws_bg);
                break;
            case 'E':
                read_color(&colors.inactive_ws_fg);
                break;
            case 'F':
                read_color(&colors.inactive_ws_bg);
                break;
            case 'G':
                read_color(&colors.urgent_ws_bg);
                break;
            case 'H':
                read_color(&colors.urgent_ws_fg);
                break;
            case 'I':
                read_color(&colors.focus_ws_bg);
                break;
            case 'J':
                read_color(&colors.focus_ws_fg);
                break;
            default:
                print_usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
        }
    }

    if (fontname == NULL) {
        /* This is a very restrictive default. More sensefull would be something like
         * "-misc-*-*-*-*--*-*-*-*-*-*-*-*". But since that produces very ugly results
         * on my machine, let's stick with this until we have a configfile */
        fontname = "-misc-fixed-medium-r-semicondensed--12-110-75-75-c-60-iso10646-1";
    }

    if (config.dockpos != DOCKPOS_NONE) {
        if (config.hide_on_modifier) {
            ELOG("--dock and --hide are mutually exclusive!\n");
            exit(EXIT_FAILURE);
        }
    } else {
        config.hide_on_modifier = 1;
    }

    main_loop = ev_default_loop(0);

    init_colors(&colors);
    char *atom_sock_path = init_xcb(fontname);

    if (socket_path == NULL) {
        socket_path = atom_sock_path;
    }

    if (socket_path == NULL) {
        ELOG("No Socket Path Specified, default to %s\n", i3_default_sock_path);
        socket_path = expand_path(i3_default_sock_path);
    }

    free_colors(&colors);

    init_outputs();
    if (init_connection(socket_path)) {
        /* We subscribe to the i3-events we need */
        subscribe_events();

        /* We initiate the main-function by requesting infos about the outputs and
         * workspaces. Everything else (creating the bars, showing the right workspace-
         * buttons and more) is taken care of by the event-driveniness of the code */
        i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_OUTPUTS, NULL);
        if (!config.disable_ws) {
            i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_WORKSPACES, NULL);
        }
    }

    /* The name of this function is actually misleading. Even if no -c is specified,
     * this function initiates the watchers to listen on stdin and react accordingly */
    start_child(command);
    FREE(command);

    /* We listen to SIGTERM/QUIT/INT and try to exit cleanly, by stopping the main-loop.
     * We only need those watchers on the stack, so putting them on the stack saves us
     * some calls to free() */
    ev_signal *sig_term = malloc(sizeof(ev_signal));
    ev_signal *sig_int = malloc(sizeof(ev_signal));
    ev_signal *sig_hup = malloc(sizeof(ev_signal));

    if (sig_term == NULL || sig_int == NULL || sig_hup == NULL) {
        ELOG("malloc() failed: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    ev_signal_init(sig_term, &sig_cb, SIGTERM);
    ev_signal_init(sig_int, &sig_cb, SIGINT);
    ev_signal_init(sig_hup, &sig_cb, SIGHUP);

    ev_signal_start(main_loop, sig_term);
    ev_signal_start(main_loop, sig_int);
    ev_signal_start(main_loop, sig_hup);

    /* From here on everything should run smooth for itself, just start listening for
     * events. We stop simply stop the event-loop, when we are finished */
    ev_loop(main_loop, 0);

    kill_child();

    FREE(statusline_buffer);

    clean_xcb();
    ev_default_destroy();

    free_workspaces();

    return 0;
}
コード例 #11
0
status_t GZipSection::Execute(ReportRequestSet* requests) const {
    // Reads the files in order, use the first available one.
    int index = 0;
    unique_fd fd;
    while (mFilenames[index] != NULL) {
        fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
        if (fd.get() != -1) {
            break;
        }
        ALOGW("GZipSection failed to open file %s", mFilenames[index]);
        index++;  // look at the next file.
    }
    VLOG("GZipSection is using file %s, fd=%d", mFilenames[index], fd.get());
    if (fd.get() == -1) {
        ALOGW("GZipSection %s can't open all the files", this->name.string());
        return NO_ERROR;  // e.g. LAST_KMSG will reach here in user build.
    }
    FdBuffer buffer;
    Fpipe p2cPipe;
    Fpipe c2pPipe;
    // initiate pipes to pass data to/from gzip
    if (!p2cPipe.init() || !c2pPipe.init()) {
        ALOGW("GZipSection '%s' failed to setup pipes", this->name.string());
        return -errno;
    }

    pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
    if (pid == -1) {
        ALOGW("GZipSection '%s' failed to fork", this->name.string());
        return -errno;
    }
    // parent process

    // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
    // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
    EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
    internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
    size_t fileLen = strlen(mFilenames[index]);
    internalBuffer->writeRawVarint32(fileLen);
    for (size_t i = 0; i < fileLen; i++) {
        internalBuffer->writeRawByte(mFilenames[index][i]);
    }
    internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
                                WIRE_TYPE_LENGTH_DELIMITED);
    size_t editPos = internalBuffer->wp()->pos();
    internalBuffer->wp()->move(8);  // reserve 8 bytes for the varint of the data size.
    size_t dataBeginAt = internalBuffer->wp()->pos();
    VLOG("GZipSection '%s' editPos=%zd, dataBeginAt=%zd", this->name.string(), editPos,
         dataBeginAt);

    status_t readStatus = buffer.readProcessedDataInStream(
            fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
            isSysfs(mFilenames[index]));
    write_section_stats(requests->sectionStats(this->id), buffer);
    if (readStatus != NO_ERROR || buffer.timedOut()) {
        ALOGW("GZipSection '%s' failed to read data from gzip: %s, timedout: %s",
              this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
        kill_child(pid);
        return readStatus;
    }

    status_t gzipStatus = wait_child(pid);
    if (gzipStatus != NO_ERROR) {
        ALOGW("GZipSection '%s' abnormal child process: %s", this->name.string(),
              strerror(-gzipStatus));
        return gzipStatus;
    }
    // Revisit the actual size from gzip result and edit the internal buffer accordingly.
    size_t dataSize = buffer.size() - dataBeginAt;
    internalBuffer->wp()->rewind()->move(editPos);
    internalBuffer->writeRawVarint32(dataSize);
    internalBuffer->copy(dataBeginAt, dataSize);
    VLOG("GZipSection '%s' wrote %zd bytes in %d ms, dataSize=%zd", this->name.string(),
         buffer.size(), (int)buffer.durationMs(), dataSize);
    status_t err = write_report_requests(this->id, buffer, requests);
    if (err != NO_ERROR) {
        ALOGW("GZipSection '%s' failed writing: %s", this->name.string(), strerror(-err));
        return err;
    }

    return NO_ERROR;
}
コード例 #12
0
ファイル: controls.c プロジェクト: jordonwu/ICSim
int main(int argc, char *argv[]) {
  int opt;
  struct sockaddr_can addr;
  struct canfd_frame frame;
  int running = 1;
  int enable_canfd = 1;
  int play_traffic = 1;
  struct stat st;
  SDL_Event event;

  while ((opt = getopt(argc, argv, "Xdl:s:t:h?")) != -1) {
    switch(opt) {
	case 'l':
		difficulty = atoi(optarg);
		break;
	case 's':
		seed = atoi(optarg);
		break;
	case 't':
		traffic_log = optarg;
		break;
	case 'd':
		debug = 1;
		break;
	case 'X':
		play_traffic = 0;
		break;
	case 'h':
	case '?':
	default:
		usage(NULL);
		break;
    }
  }

  if (optind >= argc) usage("You must specify at least one can device");

  if(stat(traffic_log, &st) == -1) {
	char msg[256];
	snprintf(msg, 255, "CAN Traffic file not found: %s\n", traffic_log);
	usage(msg);
  }

  /* open socket */
  if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
       perror("socket");
       return 1;
  }

  addr.can_family = AF_CAN;

  strcpy(ifr.ifr_name, argv[optind]);
  if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
       perror("SIOCGIFINDEX");
       return 1;
  }
  addr.can_ifindex = ifr.ifr_ifindex;

  if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES,
                 &enable_canfd, sizeof(enable_canfd))){
       printf("error when enabling CAN FD support\n");
       return 1;
  }

  if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
       perror("bind");
       return 1;
  }

  door_id = DEFAULT_DOOR_ID;
  signal_id = DEFAULT_SIGNAL_ID;
  speed_id = DEFAULT_SPEED_ID;

  if (seed) {
	srand(seed);
        door_id = (rand() % 2046) + 1;
        signal_id = (rand() % 2046) + 1;
        speed_id = (rand() % 2046) + 1;
        door_pos = rand() % 9;
        signal_pos = rand() % 9;
        speed_pos = rand() % 8;
        printf("Seed: %d\n", seed);
	door_len = door_pos + 1;
	signal_len = signal_pos + 1;
	speed_len = speed_len + 2;
  }

  if(difficulty > 0) {
	if (door_len < 8) {
		door_len += rand() % (8 - door_len);
	} else {
		door_len = 0;
	}
	if (signal_len < 8) {
		signal_len += rand() % (8 - signal_len);
	} else {
		signal_len = 0;
	}
	if (speed_len < 8) {
		speed_len += rand() % (8 - speed_len);
	} else {
		speed_len = 0;
	}
  }

  if(play_traffic) {
	signal(SIGALRM,(void (*)(int))kill_child);
	play_id = fork();
	if((int)play_id == -1) {
		printf("Error: Couldn't fork bg player\n");
		exit(-1);
	} else if (play_id != 0) {
		play_can_traffic();
	}
  }

  // GUI Setup
  SDL_Window *window = NULL;
  SDL_Surface *screenSurface = NULL;
  if(SDL_Init ( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ) {
        printf("SDL Could not initializes\n");
        exit(40);
  }
  if( SDL_NumJoysticks() < 1) {
	printf(" Warning: No joysticks connected\n");
  } else {
	if(SDL_IsGameController(0)) {
	  gGameController = SDL_GameControllerOpen(0);
	  if(gGameController == NULL) {
		printf(" Warning: Unable to open game controller. %s\n", SDL_GetError() );
	  } else {
		gJoystick = SDL_GameControllerGetJoystick(gGameController);
		gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
		print_joy_info();
	  }
        } else {
		gJoystick = SDL_JoystickOpen(0);
		if(gJoystick == NULL) {
			printf(" Warning: Could not open joystick\n");
		} else {
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			if (gHaptic == NULL) printf("No Haptic support\n");
			print_joy_info();
		}
	}
  }
  window = SDL_CreateWindow("CANBus Control Panel", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
  if(window == NULL) {
        printf("Window could not be shown\n");
  }
  renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_Surface *image = IMG_Load(get_data("joypad.png"));
  base_texture = SDL_CreateTextureFromSurface(renderer, image);
  SDL_RenderCopy(renderer, base_texture, NULL, NULL);
  SDL_RenderPresent(renderer);
  int button, axis; // Used for checking dynamic joystick mappings

  while(running) {
    while( SDL_PollEvent(&event) != 0 ) {
        switch(event.type) {
            case SDL_QUIT:
                running = 0;
                break;
	    case SDL_WINDOWEVENT:
		switch(event.window.event) {
		case SDL_WINDOWEVENT_ENTER:
		case SDL_WINDOWEVENT_RESIZED:
			redraw_screen();
			break;
		}
	    case SDL_KEYDOWN:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = 1;
			break;
		    case SDLK_LEFT:
			turning = -1;
			break;
		    case SDLK_RIGHT:
			turning = 1;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_a:
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			break;
		    case SDLK_b:
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			break;
		    case SDLK_x:
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			break;
		    case SDLK_y:
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			break;
		}
		kk_check(event.key.keysym.sym);
	   	break;
	    case SDL_KEYUP:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = -1;
			break;
		    case SDLK_LEFT:
		    case SDLK_RIGHT:
			turning = 0;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 0;
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 0;
			break;
		}
		break;
	    case SDL_JOYAXISMOTION:
		axis = event.jaxis.axis;
		if(axis == gAxisLeftH) {
			ud(event.jaxis.value);
		} else if(axis == gAxisLeftV) {
			turn(event.jaxis.value);
		} else if(axis == gAxisR2) {
			accelerate(event.jaxis.value);
		} else if(axis == gAxisRightH ||
			  axis == gAxisRightV ||
			  axis == gAxisL2 ||
			  axis == gJoyX ||
			  axis == gJoyY ||
			  axis == gJoyZ) {
			// Do nothing, the axis is known just not connected
		} else {
			if (debug) printf("Unkown axis: %d\n", event.jaxis.axis);
		}
		break;
	    case SDL_JOYBUTTONDOWN:
                button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonUnlock) {
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonA) {
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			kk_check(SDLK_a);
		} else if (button == gButtonB) {
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			kk_check(SDLK_b);
		} else if (button == gButtonX) {
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			kk_check(SDLK_x);
		} else if (button == gButtonY) {
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			kk_check(SDLK_y);
		} else if (button == gButtonStart) {
			kk_check(SDLK_RETURN);
		} else {
			if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYBUTTONUP:
		button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 0;
		} else if(button == gButtonUnlock) {
			unlock_enabled = 0;
		} else {
			//if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYDEVICEADDED:
		// Only use the first controller
		if(event.cdevice.which == 0) {
			gJoystick = SDL_JoystickOpen(0);
			if(gJoystick) {
				gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
				print_joy_info();
			}
		}
		break;
	    case SDL_JOYDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_JoystickClose(gJoystick);
			gJoystick = NULL;
		}
		break;
	    case SDL_CONTROLLERDEVICEADDED:
		// Only use the first controller
		if(gGameController == NULL) {
			gGameController = SDL_GameControllerOpen(0);
			gJoystick = SDL_GameControllerGetJoystick(gGameController);
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			print_joy_info();
		}
		break;
	    case SDL_CONTROLLERDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_GameControllerClose(gGameController);
			gGameController = NULL;
		}
		break;
        }
    }
    currentTime = SDL_GetTicks();
    checkAccel();
    checkTurn();
    SDL_Delay(5);
  }

  kill_child(SIGKILL);
  close(s);
  SDL_DestroyTexture(base_texture);
  SDL_FreeSurface(image);
  SDL_GameControllerClose(gGameController);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

}
コード例 #13
0
ファイル: main.c プロジェクト: osxi/i3bgbar
int main(int argc, char **argv) {
    int opt;
    int option_index = 0;
    char *socket_path = getenv("I3SOCK");
    char *i3_default_sock_path = "/tmp/i3-ipc.sock";

    /* Initialize the standard config to use 0 as default */
    memset(&config, '\0', sizeof(config_t));

    static struct option long_opt[] = {
        { "socket",               required_argument, 0, 's' },
        { "bar_id",               required_argument, 0, 'b' },
        { "help",                 no_argument,       0, 'h' },
        { "version",              no_argument,       0, 'v' },
        { NULL,                   0,                 0, 0}
    };

    while ((opt = getopt_long(argc, argv, "b:s:hv", long_opt, &option_index)) != -1) {
        switch (opt) {
            case 's':
                socket_path = expand_path(optarg);
                break;
            case 'v':
                printf("i3bar version " I3_VERSION " © 2010-2014 Axel Wagner and contributors\n");
                exit(EXIT_SUCCESS);
                break;
            case 'b':
                config.bar_id = sstrdup(optarg);
                break;
            default:
                print_usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
        }
    }

    if (!config.bar_id) {
        /* TODO: maybe we want -f which will automatically ask i3 for the first
         * configured bar (and error out if there are too many)? */
        ELOG("No bar_id passed. Please let i3 start i3bar or specify --bar_id\n");
        exit(EXIT_FAILURE);
    }

    main_loop = ev_default_loop(0);

    char *atom_sock_path = init_xcb_early();

    if (socket_path == NULL) {
        socket_path = atom_sock_path;
    }

    if (socket_path == NULL) {
        ELOG("No Socket Path Specified, default to %s\n", i3_default_sock_path);
        socket_path = expand_path(i3_default_sock_path);
    }

    init_outputs();
    if (init_connection(socket_path)) {
        /* Request the bar configuration. When it arrives, we fill the config array. */
        i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_BAR_CONFIG, config.bar_id);
    }

    /* We listen to SIGTERM/QUIT/INT and try to exit cleanly, by stopping the main-loop.
     * We only need those watchers on the stack, so putting them on the stack saves us
     * some calls to free() */
    ev_signal *sig_term = smalloc(sizeof(ev_signal));
    ev_signal *sig_int = smalloc(sizeof(ev_signal));
    ev_signal *sig_hup = smalloc(sizeof(ev_signal));

    ev_signal_init(sig_term, &sig_cb, SIGTERM);
    ev_signal_init(sig_int, &sig_cb, SIGINT);
    ev_signal_init(sig_hup, &sig_cb, SIGHUP);

    ev_signal_start(main_loop, sig_term);
    ev_signal_start(main_loop, sig_int);
    ev_signal_start(main_loop, sig_hup);

    /* From here on everything should run smooth for itself, just start listening for
     * events. We stop simply stop the event-loop, when we are finished */
    ev_loop(main_loop, 0);

    kill_child();

    FREE(l_statusline_buffer);
    FREE(r_statusline_buffer);

    clean_xcb();
    ev_default_destroy();

    free_workspaces();

    return 0;
}
コード例 #14
0
ファイル: ap.c プロジェクト: jonathanhamm/csma
int main(int argc, char *argv[])
{
    int c, status;
    char *src;
    buf_s *in;
    struct sigaction sa;
    sym_record_s *rec, *recb;
    pthread_t req_thread;
    sigset_t mask;
    
    if(argc > 1) {
        src = readfile(argv[1]);
        parse(src);
        closefile();
    }
    else {
        src = readfile("test");
        parse(src);
        closefile();
    }
    
    name = "ap";
    name_stripped = "ap";
    name_len = sizeof("ap")-1;
    
    if(access("out/", F_OK)) {
        if(errno == ENOENT)
            mkdir("out", S_IRWXU);
        else {
            perror("Directory Access");
            exit(EXIT_FAILURE);
        }
    }
    
    logfile = fopen("out/ap", "w");
    if(!logfile) {
        perror("Error Creating file for redirection");
        exit(EXIT_FAILURE);
    }
    
    sa.sa_handler = sigUSR1;
    sa.sa_flags = SA_RESTART;
    sigemptyset(&sa.sa_mask);
    status = sigaction(SIGUSR1, &sa, NULL);
    if(status < 0) {
        perror("Error installing handler for SIGUSR1");
        exit(EXIT_FAILURE);
    }
    
    sa.sa_handler = sigALARM;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    status = sigaction(SIGALRM, &sa, NULL);
    if(status < 0) {
        perror("Error installing handler for SIGTERM");
        exit(EXIT_FAILURE);
    }

    shm_mediums = shmget(SHM_KEY_S, sizeof(*mediums), IPC_CREAT|SHM_R|SHM_W);
    if(shm_mediums < 0) {
        perror("Failed to set up shared memory segment");
        exit(EXIT_FAILURE);
    }
    
    mediums = shmat(shm_mediums, NULL, 0);
    if(mediums == (medium_s *)-1) {
        perror("Failed to attached shared memory segment.");
        exit(EXIT_FAILURE);
    }
    mediums->isbusy = false;
    
    shm_mediumc = shmget(SHM_KEY_C, sizeof(*mediumc), IPC_CREAT|SHM_R|SHM_W);
    if(shm_mediumc < 0) {
        perror("Failed to set up shared memory segment");
        exit(EXIT_FAILURE);
    }
    
    mediumc = shmat(shm_mediumc, NULL, 0);
    if(mediumc == (medium_s *)-1) {
        perror("Failed to attached shared memory segment.");
        exit(EXIT_FAILURE);
    }
    mediumc->isbusy = false;
    
    status = pthread_create(&req_thread, NULL, process_request, NULL);
    if(status) {
        perror("Failure to set up thread");
        exit(EXIT_FAILURE);
    }
    
    sigemptyset(&mask);
    sigaddset(&mask, SIGUSR2);
    status = pthread_sigmask(SIG_BLOCK, &mask, NULL);
    if(status) {
        perror("Failure to mask SIGUSR2 in parent thread.");
        exit(EXIT_FAILURE);
    }

    process_tasks();
    
    in = buf_init();
    
    /* Get command line input */
    printf("> ");
    while((c = getchar()) != EOF) {
        buf_addc(&in, c);
        if(c == '\n') {
            buf_addc(&in, '\0');
            parse(in->buf);
            process_tasks();
            buf_reset(&in);
            printf("> ");
        }
    }
    buf_free(in);
    
    pthread_mutex_lock(&station_table_lock);
    /* kill all children */
    for(c = 0; c < SYM_TABLE_SIZE; c++) {
        rec = station_table.table[c];
        while(rec) {
            kill_child(rec->data.ptr);
            recb = rec->next;
            free(rec);
            rec = recb;
        }
    }
    pthread_mutex_unlock(&station_table_lock);

    pthread_mutex_destroy(&station_table_lock);
    
    fclose(logfile);
    
    exit(EXIT_SUCCESS);
}
コード例 #15
0
ファイル: vfork.c プロジェクト: Mellanox/arc_ltp
int
main(int argc, char** argv)
{

#if HAVE_DECL_PTRACE_SETOPTIONS && HAVE_DECL_PTRACE_O_TRACEVFORKDONE
	int exit_status;

	_parse_opts(argc, argv);

	if (fp == NULL) {
		fp = stderr;
	}

	if (socketpair(AF_UNIX, SOCK_STREAM, 0, psync) == -1) {
		tst_resm(TBROK | TERRNO, "socketpair() failed");
	} else {

		child = fork();
		if (child == -1) {
			tst_resm(TBROK | TERRNO, "fork() failed");
		} else if (child == 0) {

			int rc = EXIT_FAILURE;

			tst_sig(FORK, DEF_HANDLER, child_cleanup);

			if (close(psync[1])) {
				tst_resm(TBROK, "close(psync[1]) failed)");
			} else {
				/* sleep until the parent wakes us up */
				await_mutex(psync[0]);
				rc = do_vfork(num_vforks);
			}
			_exit(rc);

		} else {

			tst_sig(FORK, kill_child, parent_cleanup);

			close(psync[0]);

			/* Set up ptrace */
			if (ptrace(PTRACE_ATTACH, child, NULL, NULL) == -1) {
				tst_resm(TBROK | TERRNO,
					 "ptrace(ATTACH) failed");
				tst_exit();
			}
			if (waitpid(child, NULL, 0) != child) {
				tst_resm(TBROK | TERRNO, "waitpid(%d) failed",
							 child);
				kill_child();
			} else {

				if (ptrace(PTRACE_SETOPTIONS, child, NULL,
					   PTRACE_O_TRACEVFORK) == -1) {
					tst_resm(TINFO | TERRNO,
						"ptrace(PTRACE_SETOPTIONS) "
						"failed.");
				}
				if (ptrace(PTRACE_CONT, child, NULL, NULL) == -1) {
					tst_resm(TINFO | TERRNO,
						"ptrace(PTRACE_CONT) failed.");
				}

				send_mutex(psync[1]);

				close(psync[1]);

				tst_resm(TINFO, "Child spawn's pid=%d", child);
				fprintf(fp, "%d\n", child);
				fflush(fp);

				exit_status = do_trace(child, ++num_vforks);

				tst_resm(exit_status == 0 ? TPASS : TFAIL,
					"do_trace %s",
					(exit_status == 0 ? "succeeded" : "failed"));

				parent_cleanup();

			}

		}

	}

#else
	tst_resm(TCONF, "System doesn't support have required ptrace "
		        "capabilities.");
#endif
	tst_resm(TINFO, "Exiting...");
	tst_exit();

}
コード例 #16
0
ファイル: run4.c プロジェクト: jazzyb/run4
void
sighandler (int sig)
{
    kill_child();
    exit(0);
}
コード例 #17
0
ファイル: menu.c プロジェクト: MarxBro/radio_bash
int main(){	
    main_pid = getpid();
    char line[BUF][BUF];
    FILE *rlist = NULL; 
    int igt     = 0;
    int total   = 0;
    rlist       = fopen("STATIONS.txt", "r");
    while( fgets ( line[igt], BUF, rlist )) {
        /* get rid of ending \n from fgets */
        line[igt][strlen(line[igt]) - 1] = '\0';
        char *line_f        = line[igt];
        uris[igt]           = strtok(line_f,    "@");
        choices[igt]        = strtok(NULL,      "@");
        descriptions[igt]   = strtok(NULL,      "@");
        igt++;
    }
    
	/* Initialize curses */	
    ITEM **my_items;
	int c;				
	MENU *my_menu;
        int n_choices, i;
	ITEM *cur_item;
	initscr();
    /*We dont really need colors for now...*/
    /*start_color();*/
        cbreak();
        noecho();
	keypad(stdscr, TRUE);
    /*wborder(0 , 0,0,0,0,0,0,0,0,);*/
    /*init_pair(1, COLOR_RED,COLOR_WHITE);*/
    /*init_pair(2, COLOR_GREEN,COLOR_WHITE);*/
    /*init_pair(3, COLOR_MAGENTA,COLOR_WHITE);*/
	/* Initialize items */
        n_choices = ARRAY_SIZE(choices);
        my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *));
        for(i = 0; i < n_choices; ++i) {
            my_items[i] = new_item(choices[i],descriptions[i]);
		    /* The F*cking user pointer */
		    set_item_userptr(my_items[i], func);
	    }
	my_items[n_choices] = (ITEM *)NULL;

	/* Create menu */
	my_menu = new_menu((ITEM **)my_items);
    set_menu_opts(my_menu,O_SHOWDESC);
    int y_lines_menu = LINES - y_lines_reserved;
    set_menu_format(my_menu,y_lines_menu,1);

	/* Post the menu */
    /*Help thingy*/
    hacete_una_linea_putin(5);
	mvprintw(LINES - 4, 0, " Press <ENTER> to play the station,");
	mvprintw(LINES - 3, 0, " any <arrow> to move the menu buffer, <Q> to Quit or");
	mvprintw(LINES - 2, 0, " <K> to Kill child mplayer process.");
    hacete_una_linea_putin(1);
	post_menu(my_menu);
	refresh();

    /*big loop thingy*/
    while((c = getch()) != 113){
        switch(c){
            case KEY_DOWN:
                menu_driver(my_menu, REQ_DOWN_ITEM);
                break;
            case KEY_UP:
                menu_driver(my_menu, REQ_UP_ITEM);
                break;
            case KEY_LEFT:
                menu_driver(my_menu, REQ_SCR_UPAGE);
                break;
            case KEY_RIGHT:
                menu_driver(my_menu, REQ_SCR_DPAGE);
                break;
            case 107:   // k
                kill_child();
                break;
            case 10: {    /* Enter  == Play some radio! */
                ITEM *cur;
                void (*p)(char *);
                if (*contador >= 1){
                    kill_child();
                }
                cur = current_item(my_menu);
                description_fn = (char *)item_description(cur);
                p = item_userptr(cur);
                p((char *)item_name(cur));
                pos_menu_cursor(my_menu);
                play_radio();
                cuenta = cuenta + 1;
                break;
            }
            break;
        }
    }
    /*That's all, free memory, kill any pid and exit.*/
    unpost_menu(my_menu);
    for(i = 0; i < n_choices; ++i){
        free_item(my_items[i]);
    }
    free_menu(my_menu);
    endwin();
    kill_child();
    exit(0);
}