Читаем UNIX — универсальная среда программирования полностью

 struct stat sti, sto;

 int fin, fout, n;

 char target[BUFSIZ], buf[BUFSIZ], *index;

 sprintf(target, "%s/%s", dir, file);

 if (index(file, '/') != NULL) /* strchr in some systems */

  error("won't handle '/'s in %s", file);

 if (stat(file, sti) == -1)

  error("can't stat %s", file);

 if (stat(target, sto) == -1) /* target not present */

  sto.st_mtime = 0; /* so make it look old */

 if (sti.st_mtime sto.st_mtime) /* target is newer */

  fprintf(stderr, "%s: %s not copied\n", progname, file);

 else if ((fin = open(file, 0)) == -1)

  error("can't open file %s", file);

 else if ((fout = creat(target, sti.st_mode)) == -1)

  error("can't create %s", target);

 while ((n = read(fin, buf, sizeof buf)) 0)

  if (write(fout, buf, n) != n)

   error("error writing %s", target);

 close(fin);

 close(fout);

}

#include "error.c"

<p>3.8.52 <code>system1.c</code></p>

#include signal.h

system(s) /* run command line s */

 char *s;

{

 int status, pid, w, tty;

 int (*istat), (*qstat);

 ...

 if ((pid = fork) == 0) {

  ...

  execlp("sh", "sh", "-c", s, (char*)0);

  exit(127);

 }

 ...

 istat = signal(SIGINT, SIG_IGN);

 qstat = signal(SIGQUIT, SIG_IGN);

 while ((w = wait(status)) != pid w != -1)

  ;

 if (w == -1)

  status = -1;

 signal(SIGINT, istat);

 signal(SIGQUIT, qstat);

 return status;

}

<p>3.8.53 <code>system.c</code></p>

/*

 * Safer version of system for interactive programs

 */

#include signal.h

#include stdio.h

system(s) /* run command line s */

 char *s;

{

 int status, pid, w, tty;

 int (*istat), (*qstat);

 extern char *progname;

 fflush(stdout);

 tty = open("/dev/tty", 2);

 if (tty == -1) {

  fprintf (stderr, "%s: can't open /dev/tty\n", progname);

  return -1;

 }

 if ((pid = fork) == 0) {

  close(0);

  dup(tty);

  close(1);

  dup(tty);

  close(2);

  dup(tty);

  close(tty);

  execlp("sh", "sh", "-c", s, (char*)0);

  exit(127);

 }

 close(tty);

 istat = signal(SIGINT, SIG_IGN);

 qstat = signal(SIGQUIT, SIG_IGN);

 while ((w = wait(status)) != pid w != -1)

  ;

 if (w == -1)

  status = -1;

 signal(SIGINT, istat);

 signal(SIGQUIT, qstat);

 return status;

}

<p>3.8.54 <code>timeout.c</code></p>

/* timeout: set time limit on a process */

#include stdio.h

#include signal.h

int pid; /* child process id */

char *progname;

main(argc, argv)

 int argc;

 char *argv[];

{

 int sec = 10, status, onalarm;

 progname = argv[0];

 if (argc 1 argv[1][0] == '-') {

  sec = atoi(argv[1][1]);

  argc--;

  argv++;

 }

 if (argc 2)

  error("Usage: %s [-10] command", progname);

 if ((pid=fork) == 0) {

  execvp(argv[1], argv[1]);

  error("couldn't start %s", argv[1]);

 }

 signal(SIGALRM, onalarm);

 alarm(sec);

 if (wait(status) == -1 || (status 0177) != 0)

  error("%s killed", argv[1]);

 exit((status 8) 0377);

}

onalarm /* kill child when alarm arrives */

{

 kill(pid, SIGKILL);

}

#include "error.c"

Перейти на страницу:

Похожие книги

1001 совет по обустройству компьютера
1001 совет по обустройству компьютера

В книге собраны и обобщены советы по решению различных проблем, которые рано или поздно возникают при эксплуатации как экономичных нетбуков, так и современных настольных моделей. Все приведенные рецепты опробованы на практике и разбиты по темам: аппаратные средства персональных компьютеров, компьютерные сети и подключение к Интернету, установка, настройка и ремонт ОС Windows, работа в Интернете, защита от вирусов. Рассмотрены не только готовые решения внезапно возникающих проблем, но и ответы на многие вопросы, которые возникают еще до покупки компьютера. Приведен необходимый минимум технических сведений, позволяющий принять осознанное решение.Компакт-диск прилагается только к печатному изданию книги.

Юрий Всеволодович Ревич

Программирование, программы, базы данных / Интернет / Компьютерное «железо» / ОС и Сети / Программное обеспечение / Книги по IT