void verrx(int eval, const char *fmt, va_list ap) { if (err_file == NULL) err_set_file(NULL); fprintf(err_file, "%s: ", _getprogname()); if (fmt != NULL) vfprintf(err_file, fmt, ap); fprintf(err_file, "\n"); if (err_exit) err_exit(eval); exit(eval); }
int main(void) { int err; pthread_t tid1, tid2; struct foo *fp; err = pthread_create(&tid1, NULL, thr_fn1, NULL); if (err != 0) err_exit(err, "can't create thread 1"); err = pthread_join(tid1, (void *)&fp); if (err != 0) err_exit(err, "can't join with thread 1"); sleep(1); printf("parent starting second thread\n"); err = pthread_create(&tid2, NULL, thr_fn2, NULL); if (err != 0) err_exit(err, "can't create thread 2"); sleep(1); printfoo("parent:\n", fp); exit(0); }
int main(void) { int err; pthread_t tid1, tid2; void *tret; err = pthread_create(&tid1, NULL, thr_fn1, (void *)1); if (err != 0) err_exit(err, "can't create thread 1"); err = pthread_create(&tid2, NULL, thr_fn2, (void *)1); if (err != 0) err_exit(err, "can't create thread 2"); err = pthread_join(tid1, &tret); if (err != 0) err_exit(err, "can't join with thread 1"); printf("thread 1 exit code %ld\n", (long)tret); err = pthread_join(tid2, &tret); if (err != 0) err_exit(err, "can't join with thread 2"); printf("thread 2 exit code %ld\n", (long)tret); exit(0); }
void extract_mtk_boot(const char *filename, const char *outname) { char buf[MTK_PBL_SIZE]; int n; FILE *in = fopen(filename, "rb"); if (in == NULL) err_exit("Can't open file %s\n", filename); FILE *out = fopen(outname, "wb"); if (out == NULL) err_exit("Can't open file %s for writing\n", outname); n = fread(&buf, 1, MTK_PBL_SIZE, in); if (n != MTK_PBL_SIZE) { fclose(in); err_exit("Error: PBL size mismatch!\n"); } fclose(in); fwrite(&buf, 1, MTK_PBL_SIZE, out); fclose(out); }
/* * Execute lstopo from user's PATH sending full topology XML over stdin. * Pass any extra options along to lstopo(1). * * If running lstopo fails with ENOENT, try lstopo-no-graphics. */ static int exec_lstopo (optparse_t *p, int ac, char *av[], const char *topo) { int status; FILE *fp; char *argz; size_t argz_len; pid_t pid; const char *cmds[] = { "lstopo", "lstopo-no-graphics", NULL }; const char **cp = cmds; /* Ignore SIGPIPE so we don't get killed when exec() fails */ signal (SIGPIPE, SIG_IGN); /* Initialize argz with first command in cmds above: */ lstopo_argz_init ((char *) *cp, &argz, &argz_len, av+1); while (true) { const char *next = *(cp+1); if (!(fp = argz_popen (argz, argz_len, &pid))) err_exit ("popen (lstopo)"); fputs (topo, fp); fclose (fp); if (waitpid (pid, &status, 0) < 0) err_exit ("waitpid"); /* Break out of loop if exec() was succcessful, failed with * an error other than "File not found", or we ran out programs * to try. */ if (status == 0 || !next || WEXITSTATUS (status) != ENOENT) break; /* Replace previous cmd in argz with next command to try: */ argz_replace (&argz, &argz_len, *(cp++), next, NULL); } return (status); }
int is_nfsb(const char *filename) { FILE *file = fopen(filename, "rb"); if (file == NULL) err_exit("Can't open file %s\n\n", filename); char header[0x11]; if (fread(&header, 1, sizeof(header), file) != sizeof(header)) return 0; fclose(file); if (memcmp(&header, "NFSB", 4) == 0) return !memcmp(&header[0xE], "md5", 3); return 0; }
/* save current score in the score file */ void save_score(const int time_taken) { time_t tm = time(NULL); struct tm *today = localtime(&tm); char tmpbuffer[129]; today = localtime(&tm); char appdata_dir[4096]; //XXX why _PC_PATH_MAX is only 4? const char *score_filename = "4digits.4digits.scores"; strcpy(appdata_dir, getenv("HOME")); strcat(appdata_dir, "/.4digits/"); char *scorefile = (char*)malloc(strlen(appdata_dir) + strlen(score_filename) + 1); if(!scorefile) err_exit(_("Memory allocation error.\n")); strcpy(scorefile, appdata_dir); strcat(scorefile, score_filename); FILE *sfp = fopen(scorefile, "a+"); if (!sfp) { if (errno == ENOENT) { DIR *dp = opendir(appdata_dir); if(!dp) if (errno == ENOENT) { int ret = mkdir(appdata_dir, 0700); if (ret == -1) err_exit(_("Cannot open score file.\n")); sfp = fopen(scorefile, "a+"); } } else err_exit(_("Cannot open score file.\n")); } strftime(tmpbuffer, 128, "%a %b %d %H:%M:%S %Y", today); struct passwd *pwd; pwd = getpwuid(geteuid()); // but getenv("USERNAME") conforms to C99 thus is more portable. fprintf(sfp, "%s %ds %s\n", pwd->pw_name, time_taken, tmpbuffer); free(scorefile); }
int main(int argc,cahr ** argv) { int err; pthread_t tid; char *cmd; struct sigaction sa; if((cmd=strrchr(argv[0],'/'))==NULL) cmd=argv[0]; else cmd++; daemonize(cmd); if(already_running()) { syslog(LOG_ERR,"daemon already running"); exit(1); } sa.sa_handler=SIG_DEL; sigemptyset(&sa.sa_mask); sa.sa_flags=0; if(sigaction(SIGHUP,&sa,NULL)<0) err_quit("%s:can't restore SIGHUP default"); sigfillset(&mask); if((err=pthread_sigmask(SIG_BLOCK,&mask,NULL))!=0) err_exit(err,"SIG_BLOCK error"); err=pthread_create(&tid,NULL,thr_fn,0); if(err!=0) err_exit(err,"can't create the thread"); exit(0); }
/* * Store the file descriptor to the '*sockfd' which is connected to * server already. and return the socket file descriptor also. */ int dlinfo_connect(struct dlinfo *dl) { int s; int fd; struct addrinfo hints; struct addrinfo *res; struct addrinfo *ai; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; errno = 0; if ((s = getaddrinfo(dl->di_host, dl->di_serv, &hints, &res)) != 0) err_exit("getaddrinfo: %s, host: %s:%s", gai_strerror(s), dl->di_host, dl->di_serv); for (ai = res; ai; ai = ai->ai_next) { if ((fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { err_sys("socket"); continue; } if (connect(fd, ai->ai_addr, ai->ai_addrlen) == 0) break; err_sys("connect"); if (close(fd) == -1) err_sys("close"); } if (NULL == ai) err_exit("Couldn't connection to: %s", dl->di_host); freeaddrinfo(res); return fd; }
int main(int argc, char *argv[]) { int fd, fd2; unsigned short sectors, dummy; long size, addr1, padd_size, i; unsigned char ch; if (argc == 1) { fprintf(stderr, "Usage: imgsize PNX_IMG ADDR1\n"); return 0; } if ((fd = open(argv[1], O_RDWR)) < 0) err_exit(1); if ((fd2 = open("ifem.bin", O_RDWR)) < 0) err_exit(1); if ((addr1 = lseek(fd2,0,SEEK_END)) < 0) err_exit(1); addr1 += 0x600; close(fd2); if ((size = lseek(fd,0,SEEK_END)) < 0) err_exit(1); sectors = (size - 512) / 512 + 1; if (lseek(fd, 2, SEEK_SET) < 0) err_exit(1); if (write(fd, (char *)§ors, sizeof(sectors)) <= 0) err_exit(1); if (write(fd, (char *)&addr1, sizeof(addr1)) <= 0) err_exit(1); padd_size = size % 512; if (lseek(fd, 0, SEEK_END) < 0) err_exit(1); for (ch=0, i=padd_size; i>0; i--) if (write(fd, &ch, 1) < 0) err_exit(1); close(fd); fprintf(stderr, "===============\n"); fprintf(stderr, "ImgSize Report:\n"); fprintf(stderr, "===============\n"); fprintf(stderr, "Kernel image size = %ld bytes\n", size); fprintf(stderr, "Kernel image size = %d sectors\n", sectors); fprintf(stderr, "Padding size = %ld bytes\n", padd_size); fprintf(stderr, "Kernel image successfully modified!\n"); return 0; }
/* Changing the msg_qbytes setting of a System V message queue */ int main(int argc, char *argv[]) { struct msqid_ds ds; int msqid; if (argc != 3 || strcmp(argv[1], "--help") == 0) usage_err("%s msqid max-bytes\n", argv[0]); /* Retrive copy of associate data struct from kernel */ msqid = get_int(argv[1], 0, "msqid"); if (msgctrl(msqid, IPC_STAT, &ids) == -1) err_exit("msgctl"); d.msg_qbytes = get_int(argv[2], 0, "max-bytes"); /* Update associated data structure in kernel */ if (msgctl(msqid, IPC_SET, &ds) == -1) err_exit("msgctl"); exit(EXIT_SUCCESS); }
dll_t * init_double_link( ) { dll_t *dll; dll = (dll_t*)calloc(1,sizeof(dll_t)); if(dll == NULL) { err_exit("calloc error\n"); } dll->prev = dll;/*??prev == NULL or prev = itself??*/ dll->next = dll; return dll; }
int isSTRfile(const char *filename) { FILE *file = fopen(filename, "rb"); if (file == NULL) { err_exit("Can't open file %s\n", filename); } size_t headerSize = 0xC0 * 4; unsigned char buffer[headerSize]; int read = fread(&buffer, 1, headerSize, file); int result = 0; if (read == headerSize && buffer[4] == 0x47 && buffer[0xC0 + 4] == 0x47 && buffer[0xC0 * 2 + 4] == 0x47 && buffer[0xC0 * 3 + 4] == 0x47) result = 1; fclose(file); return result; }
int main (int argc, char *argv[]) { flux_t h; int ch; bool uopt = false; bool dopt = false; fmt_t fmt = FMT_RANGED; ns_t *ns; log_init ("flux-up"); while ((ch = getopt_long (argc, argv, OPTIONS, longopts, NULL)) != -1) { switch (ch) { case 'c': /* --comma */ fmt = FMT_COMMA; break; case 'n': /* --newline */ fmt = FMT_NEWLINE; break; case 'u': /* --up */ uopt = true; break; case 'd': /* --down */ dopt = true; break; default: usage (); break; } } if (optind != argc) usage (); if (!(h = flux_open (NULL, 0))) err_exit ("flux_open"); if (!(ns = ns_fromkvs (h))) ns = ns_guess (h); if (dopt) ns_print_down (ns, fmt); else if (uopt) ns_print_up (ns, fmt); else ns_print_all (ns, fmt); ns_destroy (ns); flux_close (h); log_fini (); return 0; }
/* * * Read from input stream the field from current position upto and including next delimiter. * */ static void push2queueout(struct streams *s, struct queues *q, int c) { int i,len; struct streams *t; t=&outstream; queuec_siz=QUEUEC_S; q->cont=malloc(queuec_siz*sizeof(char)); if (q->cont==NULL) err_exit(ERR_PRO_QUE); len=0; while ((i=fgetc(s->fp)) != c) { if (len+1 > queuec_siz) { queuec_siz*=2; q->cont=realloc(q->cont,queuec_siz*sizeof(char)); if (q->cont==NULL) err_exit(ERR_PRO_QUE); } q->cont[len++]=i; } q->cont[len]='\0'; if (c != *(s->delim)) ungetc(i,s->fp); fprintf(t->fp,"%s",q->cont); }
void extract_kernel(const char *image_file, const char *destination_file) { FILE *file = fopen(image_file, "rb"); if (file == NULL) err_exit("Can't open file %s", image_file); fseek(file, 0, SEEK_END); int fileLength = ftell(file); rewind(file); unsigned char *buffer = malloc(fileLength); int read = fread(buffer, 1, fileLength, file); if (read != fileLength) { err_exit("Error reading file. read %d bytes from %d.\n", read, fileLength); free(buffer); } fclose(file); struct image_header *image_header = (struct image_header *)(&buffer); FILE *out = fopen(destination_file, "wb"); int header_size = sizeof(struct image_header); fwrite(buffer + header_size, 1, read - header_size, out); free(buffer); fclose(out); }
/* Timer pops every 1 ms, writing a new value to key. * After 10 calls, it calls kvs_unwatch(). * After 20 calls, it calls flux_reactor_stop(). * The kvs_unwatch_cb() counts the number of times it is called, should be 10. */ void test_unwatch (int argc, char **argv) { flux_t h; char *key; int count = 0; if (argc != 1) { fprintf (stderr, "Usage: unwatch key\n"); exit (1); } key = argv[0]; if (!(h = flux_open (NULL, 0))) err_exit ("flux_open"); if (kvs_watch_int (h, key, unwatch_watch_cb, &count) < 0) err_exit ("kvs_watch_int %s", key); if (flux_tmouthandler_add (h, 1, false, unwatch_timer_cb, key) < 0) err_exit ("flux_tmouthandler_add"); if (flux_reactor_start (h) < 0) err_exit ("flux_reactor_start"); if (count != 10) msg_exit ("watch called %d times (should be 10)", count); flux_close (h); }
static void _start_cmd (void) { uint8_t timer_state; if (_get_watchdog_timer_cmd (NULL, &timer_state, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL) < 0) _ipmi_err_exit ("Get Watchdog Timer Error"); if (!timer_state) { if (_reset_watchdog_timer_cmd () < 0) _ipmi_err_exit ("Reset Watchdog Timer Error"); } if (cmd_args.gratuitous_arp || cmd_args.arp_response) { uint8_t gratuitous_arp, arp_response; int ret; if (cmd_args.gratuitous_arp) gratuitous_arp = cmd_args.gratuitous_arp_arg; else gratuitous_arp = IPMI_BMC_GENERATED_GRATUITOUS_ARP_DO_NOT_SUSPEND; if (cmd_args.arp_response) arp_response = cmd_args.arp_response_arg; else arp_response = IPMI_BMC_GENERATED_ARP_RESPONSE_DO_NOT_SUSPEND; if ((ret = _suspend_bmc_arps_cmd (gratuitous_arp, arp_response)) < 0) _ipmi_err_exit ("Suspend BMC ARPs Error"); if (!ret) err_exit ("cannot suspend BMC ARPs"); } }
static int _cb_host (conffile_t cf, struct conffile_data *data, char *optionname, int option_type, void *option_ptr, int option_data, void *app_ptr, int app_data) { if (!hostlist_push (conf.hosts, data->string)) err_exit ("hostlist_push: %s", strerror (errno)); return (0); }
static void attach_stdin_ready_cb (flux_reactor_t *r, flux_watcher_t *w, int revents, void *arg) { int fd = flux_fd_watcher_get_fd (w); ctx_t *ctx = arg; char *buf = xzmalloc (ctx->blocksize); int len; do { if ((len = read (fd, buf, ctx->blocksize)) < 0) { if (errno != EAGAIN) err_exit ("read stdin"); } else if (len > 0) { if (kz_put (ctx->kz[0], buf, len) < 0) err_exit ("kz_put"); } } while (len > 0); if (len == 0) { /* EOF */ if (kz_close (ctx->kz[0]) < 0) err_exit ("kz_close"); } free (buf); }
FILE * argz_popen (char *argz, size_t argz_len, pid_t *pidptr) { int pfds[2]; pid_t pid; if (pipe (pfds) < 0) err_exit ("pipe"); switch ((pid = fork ())) { case -1: err_exit ("fork"); case 0: close (pfds[1]); dup2 (pfds[0], STDIN_FILENO); argz_execp (argz, argz_len); if (errno != ENOENT) err ("exec"); exit (errno); /* So we can detect ENOENT.. Sorry */ default: break; } close (pfds[0]); *pidptr = pid; return (fdopen (pfds[1], "w")); }
int main (int argc, char *argv[]) { int n; FILE *from, *to; char buf[BUFSIZ] ; if (argc != 3) { /*檢查參數。*/ fprintf(stderr, "Usage : %s from-file to-file\n", *argv) ; exit (1); } if ((from = fopen(argv[1],"r")) == NULL) /* 為讀而開啟檔案from */ err_exit (argv[1] ) ; /* 以加入模式開啟檔案to. 若此檔案不存在,fopen 將建立它。*/ if ((to=fopen(argv[2], "a")) == NULL) err_exit(argv[2] ) ; /* 現在每次可以從檔案from讀入並寫至to. 注意我們寫出的字元個數是實際讀入 的字元個數而不總是BUFSIZ位元組。*/ while ((n = fread(buf, sizeof(char),BUFSIZ,from)) > 0) fwrite (buf, sizeof(char),n,to) ; /*關閉檔案*/ fclose (from) ; fclose (to) ; exit (0) ; }
void config_dump (flux_conf_t cf, int ac, char **av) { flux_conf_itr_t itr; const char *key, *val; if (ac > 0) msg_exit ("dump accepts no arguments"); itr = flux_conf_itr_create (cf); while ((key = flux_conf_next (itr))) { if (!(val = flux_conf_get (cf, key))) err_exit ("%s", key); printf("%s=%s\n", key, val); } flux_conf_itr_destroy (itr); }
int main(void) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) err_exit(err, "can't install fork handlers"); if ((err = pthread_create(&tid, NULL, thr_fn, 0)) != 0) err_exit(err, "can't create thread"); sleep(2); printf("parent about to fork...\n"); if ((pid = fork()) < 0) err_quit("fork failed"); else if (pid == 0) /* child */ printf("child returned from fork\n"); else /* parent */ printf("parent returned from fork\n"); exit(0); }
int main(int argc, char *argv[]) { if (argc > 1 && strcmp(argv[1], "--help") == 0) usage_err("%s [dir...]\n", argv[0]); if (argc == 1) /* No arguments - use current directory */ list_files('.'); else for (argv++; *argv; argv++) list_files(*argv); err_exit(EXIT_SUCCESS); }
int main(void) { char msg[200]; int start_tics, i, j, sq, max=0, count=0, primecnt=0, maxprime=1000000000; char *sieve; start_tics = clock(); /* Construct a sieve of Eratosthenes; our limit is a billion, since no */ /* pandigital number could have more than nine digits */ sieve = calloc(maxprime+1, /* allocate space for the sieve */ sizeof(char)); if (sieve == NULL) err_exit("error: cannot allocate space for sieve[]!", 1); sieve[0] = 0; /* 0 and 1 are not primes */ sieve[1] = 0; for (i=2; i<=maxprime; i++) /* fill the rest of the sieve */ sieve[i] = 1; /* with ones */ sq = sqrt(maxprime); for (i=0; i<=sq; i++) /* for each run of the loop, the first */ { /* value of i with sieve[i] != 0 */ if (sieve[i] != 0) /* is the next prime number */ for (j=i*i; j<=maxprime; j+=i)/* so strike out all multiples */ sieve[j] = 0; /* of that prime starting with */ } /* its square (lower multiples */ /* were taken care of earlier) */ for (i=0; i<=maxprime; i++) /* count the primes we found */ if (sieve[i] != 0) primecnt++; sprintf(msg, "to build the sieve of primes up to %d containing %d primes", maxprime, primecnt); logcputime(start_tics, msg); for (i=1; i<maxprime; i++) /* now search the primes for */ { /* pandigital numbers */ if ( (sieve[i] != 0) && (ispandigital(i)) ) { count++; max = i; /* the latest found will be the max */ } } sprintf(msg, "there are %d pandigital primes, and the largest is: %d", count, max); logcputime(start_tics, msg); exit(0); }
int main(int argc, char **argv) { FILE *fp; int opt, verbose = 0; char *file; file = NULL; while ((opt = getopt(argc, argv, "f:v")) != -1) { switch (opt) { case 'f': file = optarg; break; case 'v': verbose = 1; break; default: err_exit("Unexpected case in option handling"); break; } } if (optind != argc) { if (file != NULL) err_exit("Multiple input files specified"); else file = argv[optind]; } if (file == NULL) fp = stdin; else if ((fp = fopen(file, "r")) == NULL) ferr_exit("Opening file", fp); parse(fp); patch(); if (verbose) print_tree(parse_tree, 0); return 0; }
static void dump_kvs_dir (flux_t h, bool ropt, const char *path) { kvsdir_t *dir; kvsitr_t *itr; const char *name; char *key; if (kvs_get_dir (h, &dir, "%s", path) < 0) err_exit ("%s", path); itr = kvsitr_create (dir); while ((name = kvsitr_next (itr))) { key = kvsdir_key_at (dir, name); if (kvsdir_issymlink (dir, name)) { char *link; if (kvs_get_symlink (h, key, &link) < 0) err_exit ("%s", key); printf ("%s -> %s\n", key, link); free (link); } else if (kvsdir_isdir (dir, name)) { if (ropt) dump_kvs_dir (h, ropt, key); else printf ("%s.\n", key); } else { char *json_str; if (kvs_get (h, key, &json_str) < 0) err_exit ("%s", key); dump_kvs_val (key, json_str); free (json_str); } free (key); } kvsitr_destroy (itr); kvsdir_destroy (dir); }
static void init(void) { setbuf(stdout, NULL); sigset_t sigs_all; sigfillset(&sigs_all); if (sigprocmask(SIG_SETMASK, &sigs_all, (sigset_t *)NULL) == -1) err_exit(msg_init); secure_bytes = (unsigned char *)memalign(SECURE_SPACE_BLOCK_BYTE_COUNT, SECURE_SPACE_BYTE_COUNT * sizeof(unsigned char)); #ifdef _POSIX_MEMLOCK_RANGE if (mlock(secure_bytes, SECURE_SPACE_BYTE_COUNT * sizeof(unsigned char)) == -1 || mlock(&ecrypt_struct, sizeof(ECRYPT_ctx)) == -1) err_exit(msg_init); #endif struct sigaction sa = { .sa_handler = sig_handler, .sa_mask = sigs_all, .sa_flags = SA_RESTART }; if (sigaction(SIGINT, &sa, (struct sigaction *)NULL) == -1 || sigaction(SIGTERM, &sa, (struct sigaction *)NULL) == -1) err_exit(msg_init); sigset_t sigs_allowed; sigemptyset(&sigs_allowed); sigaddset(&sigs_allowed, SIGINT); sigaddset(&sigs_allowed, SIGTERM); sigaddset(&sigs_allowed, SIGSEGV); if (sigprocmask(SIG_UNBLOCK, &sigs_allowed, (sigset_t *)NULL) == -1) err_exit(msg_init); if (received_sig) err_exit(msg_sig); }
int main(int argc, char *argv[]) { int fd, r_fd; char *data; struct timeval tv1, tv2; int count = 0; int ret; int w_bytes; data = (char *) malloc (ONE_MB); if (!data) err_exit ("malloc failed\n"); if ((fd = open (argv[1], O_RDWR | O_CREAT | O_EXCL, S_IRWXU )) == -1) err_exit ("open failed\n"); if ((r_fd = open ("/dev/urandom", O_RDONLY)) == -1) err_exit ("opening urandom failed\n"); while (count < ONE_MB) { if ((ret = read (r_fd, data, 1024)) == -1) err_exit ("read failed\n"); count += ret; } /* buffered writes */ gettimeofday (&tv1, NULL); printf ("sec=%zu,ms= %zu\n", tv1.tv_sec, tv1.tv_usec); if ((w_bytes = write (fd, data, count)) != count) err_exit ("write failed\n"); /* if (fsync(fd) == -1) err_exit ("fsync failed\n"); */ gettimeofday (&tv2, NULL); printf ("sec= %zu, ms=%zu\n",tv2.tv_sec, tv2.tv_usec); printf ("total time taken for write is %zu\n", (tv2.tv_sec - tv1.tv_sec)); }