github.com/wangyougui/gf/v2@v2.6.5/os/gproc/gproc_comm_send.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gproc
     8  
     9  import (
    10  	"io"
    11  
    12  	"github.com/wangyougui/gf/v2/errors/gerror"
    13  	"github.com/wangyougui/gf/v2/internal/json"
    14  	"github.com/wangyougui/gf/v2/net/gtcp"
    15  )
    16  
    17  // Send sends data to specified process of given pid.
    18  func Send(pid int, data []byte, group ...string) error {
    19  	msg := MsgRequest{
    20  		SenderPid:   Pid(),
    21  		ReceiverPid: pid,
    22  		Group:       defaultGroupNameForProcComm,
    23  		Data:        data,
    24  	}
    25  	if len(group) > 0 {
    26  		msg.Group = group[0]
    27  	}
    28  	msgBytes, err := json.Marshal(msg)
    29  	if err != nil {
    30  		return err
    31  	}
    32  	var conn *gtcp.PoolConn
    33  	conn, err = getConnByPid(pid)
    34  	if err != nil {
    35  		return err
    36  	}
    37  	defer conn.Close()
    38  	// Do the sending.
    39  	var result []byte
    40  	result, err = conn.SendRecvPkg(msgBytes, gtcp.PkgOption{
    41  		Retry: gtcp.Retry{
    42  			Count: 3,
    43  		},
    44  	})
    45  	if len(result) > 0 {
    46  		response := new(MsgResponse)
    47  		if err = json.UnmarshalUseNumber(result, response); err == nil {
    48  			if response.Code != 1 {
    49  				err = gerror.New(response.Message)
    50  			}
    51  		}
    52  	}
    53  	// EOF is not really an error.
    54  	if err == io.EOF {
    55  		err = nil
    56  	}
    57  	return err
    58  }