2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2018-05-20 13:49:02 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2018-05-20 13:49:02 +08:00
|
|
|
|
|
|
|
package gproc
|
|
|
|
|
|
|
|
import (
|
2021-11-15 20:49:02 +08:00
|
|
|
"io"
|
|
|
|
|
2021-10-11 21:41:56 +08:00
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
|
|
"github.com/gogf/gf/v2/internal/json"
|
|
|
|
"github.com/gogf/gf/v2/net/gtcp"
|
2018-05-20 13:49:02 +08:00
|
|
|
)
|
|
|
|
|
2019-12-11 21:22:41 +08:00
|
|
|
// Send sends data to specified process of given pid.
|
2019-06-19 09:06:52 +08:00
|
|
|
func Send(pid int, data []byte, group ...string) error {
|
2019-12-11 21:22:41 +08:00
|
|
|
msg := MsgRequest{
|
2022-02-16 20:51:39 +08:00
|
|
|
SenderPid: Pid(),
|
|
|
|
ReceiverPid: pid,
|
|
|
|
Group: defaultGroupNameForProcComm,
|
|
|
|
Data: data,
|
2019-06-15 21:41:20 +08:00
|
|
|
}
|
|
|
|
if len(group) > 0 {
|
|
|
|
msg.Group = group[0]
|
|
|
|
}
|
|
|
|
msgBytes, err := json.Marshal(msg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-12-13 17:40:29 +08:00
|
|
|
var conn *gtcp.PoolConn
|
2019-12-11 21:22:41 +08:00
|
|
|
conn, err = getConnByPid(pid)
|
|
|
|
if err != nil {
|
2019-06-15 21:41:20 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
2019-12-11 21:22:41 +08:00
|
|
|
// Do the sending.
|
|
|
|
var result []byte
|
2019-12-13 17:40:29 +08:00
|
|
|
result, err = conn.SendRecvPkg(msgBytes, gtcp.PkgOption{
|
|
|
|
Retry: gtcp.Retry{
|
|
|
|
Count: 3,
|
|
|
|
},
|
|
|
|
})
|
2019-12-11 21:22:41 +08:00
|
|
|
if len(result) > 0 {
|
|
|
|
response := new(MsgResponse)
|
2021-07-20 23:02:02 +08:00
|
|
|
if err = json.UnmarshalUseNumber(result, response); err == nil {
|
2019-12-11 21:22:41 +08:00
|
|
|
if response.Code != 1 {
|
2021-06-26 18:34:26 +08:00
|
|
|
err = gerror.New(response.Message)
|
2019-12-11 21:22:41 +08:00
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
}
|
2019-12-11 21:22:41 +08:00
|
|
|
// EOF is not really an error.
|
2019-06-19 09:06:52 +08:00
|
|
|
if err == io.EOF {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
return err
|
2018-05-20 13:49:02 +08:00
|
|
|
}
|