开发者

Obj-C: system("echo -e ...") and cron without mail

开发者 https://www.devze.com 2023-04-05 08:17 出处:网络
In a small backup utility, I\'m trying to use system() to write to the user cron table in objective-c.

In a small backup utility, I'm trying to use system() to write to the user cron table in objective-c.

Now I'm doing this:

NSString *croncmd = [NSString stringWithFormat:@"echo -e 'MAILTO=\"\" \n*/1 * * * * \"%@/Library/Application Support/LBKP/cron/croncall\" %@ > /dev/null 2>&1' | crontab" , NSHomeDirectory(), backup_id ];

system([croncmd UTF8String]);

As you can see, first I simply tried to use > /dev/null 2>&1 to get rid of the mails in case of error... but in OSX seems like it doesn't work at all and I still get emails.

Then reading some info online I just come across 开发者_高级运维the usage of MAILTO="" at the start of the cron table to discard all the outputs.

The problem is that I need to echo a "new line" to the crontab file witch can usually be made using the -e option and \n char in the terminal, but if I do it from my program I get this in the console:

17/09/11 16:32:52,590 [0x0-0x3a03a].com.home.LBKP: "-":0: bad minute

What's the problem? :S How can I get rid of this error or just the output?

Thanks!


I just discovered that the problem was caused when I added quotes and other things to make the NSString... Anyway I found that the safest way to do this is:

NSString *disbl_mail = @"echo 'MAILTO=\"\"' | crontab"; // Disable all cron mail...
system([disbl_mail UTF8String]);

NSString *croncmd = [NSString stringWithFormat:@"(crontab -l; echo '*/1 * * * * \"%@/Library/Application Support/LBKP/cron/croncall\" %@ > /dev/null 2>&1') | crontab -" , NSHomeDirectory(), backup_id ];
system([croncmd UTF8String]);

The second command syntax (crontab -l; echo lists the available info on the cron table and then echoes it and the new command back to the cron. This way the previous MAILTO="" entry will not be deleted.

Anyway, and specially because I know this is not the best way to add stuff to the crontab I'm posting a new question here: Obj-C: What is the best way to add jobs to crontab?.

Hope this can me useful to someone!

0

精彩评论

暂无评论...
验证码 换一张
取 消