-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmdlist.c
101 lines (83 loc) · 2.36 KB
/
cmdlist.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "jobfork.h"
#include <ctype.h>
#include <fcntl.h>
#ifdef CMD_MPI
#include <mpi.h>
#endif
int read_jobs(const char *fname) {
FILE *fp;
char line[CMD_BUF];
char *buf;
int i, n, maxlen;
if (!(fp = fopen(fname, "r"))) {
MSG_ERR("cannot open the job list file `%s'.\n", fname);
return ERR_FILE;
}
/* count the number and maximum length of commands */
n = maxlen = 0;
memset(line, 0, CMD_BUF);
while (fgets(line, CMD_BUF, fp) != NULL) {
sscanf(line, "%*[ |\t]%[^\n]", line); /* remove leading spaces */
if (line[0] != COMMENT && isgraph(line[0])) {
buf = memchr(line, '\n', CMD_BUF);
if (buf == NULL) {
MSG_ERR("command length exceeds CMD_BUF.\n");
return ERR_STRING;
}
i = buf - line + 1;
if (maxlen < i) maxlen = i;
n++;
}
memset(line, 0, CMD_BUF);
}
if (n < 1) {
MSG_ERR("job not found.\n");
return ERR_FILE;
}
cstat.num = n;
cstat.len = maxlen;
cstat.cmd = calloc((size_t) n * maxlen, sizeof(char));
if (!(cstat.cmd)) {
MSG_ERR("failed to allocate memory for the commands.\n");
return ERR_MEMORY;
}
/* read commands into array */
fseek(fp, 0, SEEK_SET);
n = 0;
while (fgets(line, CMD_BUF, fp) != NULL) {
sscanf(line, "%*[ |\t]%[^\n]", line); /* remove leading spaces */
if (line[0] != COMMENT && isgraph(line[0])) {
line[strcspn(line, "\r\n")] = '\0';
buf = cstat.cmd + n * maxlen;
strncpy(buf, line, maxlen);
n++;
}
memset(line, 0, CMD_BUF);
}
fclose(fp);
return 0;
}
void save_jobs(void) {
if (term == 1) return; /* this function should only run for once */
else term = 1;
int i, cnt, logfile;
char *cmd;
for (cnt = 0, i = 0; i < cstat.num; i++) {
if (cstat.status[i] != JOB_DONE) cnt++;
}
if (cnt == 0) return; /* no failed job */
if (!(cstat.status && cstat.cmd)) return;
logfile = open(cstat.fname_rst, O_WRONLY | O_CREAT | O_TRUNC, 0644);
write(logfile, "# Unfinished jobs\n", 18);
for (i = 0; i < cstat.num; i++) {
if (cstat.status[i] != JOB_DONE) {
cmd = cstat.cmd + i * cstat.len;
write(logfile, cmd, strlen(cmd));
write(logfile, "\n", 1);
}
}
write(STDOUT_FILENO, "Restart file created:\n ", 24);
write(STDOUT_FILENO, cstat.fname_rst, strlen(cstat.fname_rst));
write(STDOUT_FILENO, "\n", 1);
close(logfile);
}