I decided to try making some simple clones of the various user-space Unix utilities in an effort to learn the system-specific headers and improve my C skills. The code that follows is a clone of sleep
and I'm curious as to whether there are any pitfalls I'm overlooking (including security vulnerabilities). It compiles and seems to behave fine so there's no issue there.
The program attempts to comply with the Open Group spec for sleep
.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_TIME_DIGITS (11)
int main(int argc, char *argv[]) {
if(argc != 2) {
fprintf(stderr, "sleep: too %s operands\n",
argc < 2 ? "few" : "many");
return 1;
}
if(strnlen(argv[1], MAX_TIME_DIGITS + 1) > MAX_TIME_DIGITS) {
fprintf(stderr, "sleep: operand too long\n");
return 1;
}
int i = 0;
while(argv[1][i] && i < MAX_TIME_DIGITS) {
if(!isdigit((int)argv[1][i])) {
fprintf(stderr, "sleep: invalid operand\n");
return 1;
}
++i;
}
unsigned long int time = strtoul(argv[1], NULL, 10);
sleep(time);
return 0;
}