dongwei4444 2014-09-01 07:08
浏览 35
已采纳

执行命令中断

I'm writing an application that will run as a daemon on ubuntu 14.04. The purpose of this daemon is to run a for loop that will check for data in various database tables and if data is present it will spawn a goroutine to take various actions on various data. This is done to allow me doing tasks more often than cron allows me to schedule tasks.

An example would be if the daemon found a new row in the database table "notifications" it would spawn a new goroutine that would run until it's done, which in this case would mean running the command below:

err := exec.Command("sh","-c","php /var/app/send_notification.php").Run()

Yes. I've the need to execute some php scripts from go. I don't have the time allotted to rewrite all the php code in go just yet so I'll have to make this work somehow.

I've managed to write the daemon so it will do a mostly graceful shutdown if SIGINT is sent to it. It will let all goroutines complete their tasks so that no work is stopped halfway through which may end up causing problems.

The problem is now that as soon as SIGINT is sent to this daemon, any and all processes started by the exec.Command() is aborted right away.

http://rcrowley.org/articles/golang-graceful-stop.html

The link above is what I've used as a template for this daemon.

So my question is: Is there any way to allow an exec.Command() started in a goroutine to run until completion when the daemon receives SIGINT? If not, is there another way to go about executing a command from go and allowing it to run until completion after SIGINT is received by the daemon?

  • 写回答

1条回答 默认 最新

  • douhong6187 2014-09-01 07:36
    关注

    The newly created process will be on the same process group than your daemon. This means that by default, signal sent to your daemon will be broadcast to your created processes.

    You can force your newly created process to be in his own process group just before the command using the SysProcAttr attribute of the Cmd type.

    cmd := exec.Command("sh","-c","php /var/app/send_notification.php")
    cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid:true}
    error := cmd.Run()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写