aboutsummaryrefslogtreecommitdiff
path: root/src/misc.c
blob: 0bf72330c6ef2766115214c50937d3b61351e70b (plain)
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
/*
 * misc.c
 * (c) 2019, Jonas Gunz, jonasgunz.de
 * <Description>
 * <License>
*/

#include "misc.h"

pid_t fork_run(int _stdin, int _stdout, int _stderr, int argc, char* argv[])
{
	pid_t pid = fork();
	
	if(pid == 0) {//child
		dup2 (_stdin,  STDIN_FILENO);
		dup2 (_stdout, STDOUT_FILENO);
		dup2 (_stderr, STDERR_FILENO);

		char* arv[argc + 1];

		for(int i = 0; i < argc; i++)
			arv[i] = argv[i];

		arv[argc] = NULL;

		execv(argv[0], arv);

		printf("EXEC ERROR %i: %s\r\n", errno, strerror(errno));
		exit(1);
	}
	else {
		return pid;
	}
}


int try_write(int _fd, char *_buff, int _size, int _retry)
{
	if( _size <= 0)
		return 0;

	int written = 0;
	int cntr = 0;

	while (written != _size) {
		int ret = write ( _fd, _buff + written, _size - written);
		
		if(ret < 0)
			return 1;
		else {
			written += ret; 
			cntr = 0; //reset fail counter
		}

		if(++cntr > _retry)
			return 1;
	}
	return 0;
}