Merge changes from emacs-23 branch.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* some typedefs are used in sys/file.h */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
31 #ifdef HAVE_INTTYPES_H
32 #include <inttypes.h>
33 #endif
34
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #include <fcntl.h>
39
40 /* Only MS-DOS does not define `subprocesses'. */
41 #ifdef subprocesses
42
43 #include <sys/socket.h>
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47
48 /* Are local (unix) sockets supported? */
49 #if defined (HAVE_SYS_UN_H)
50 #if !defined (AF_LOCAL) && defined (AF_UNIX)
51 #define AF_LOCAL AF_UNIX
52 #endif
53 #ifdef AF_LOCAL
54 #define HAVE_LOCAL_SOCKETS
55 #include <sys/un.h>
56 #endif
57 #endif
58
59 #if defined(HAVE_SYS_IOCTL_H)
60 #include <sys/ioctl.h>
61 #if defined(HAVE_NET_IF_H)
62 #include <net/if.h>
63 #endif /* HAVE_NET_IF_H */
64 #endif /* HAVE_SYS_IOCTL_H */
65
66 #ifdef NEED_BSDTTY
67 #include <bsdtty.h>
68 #endif
69
70 #ifdef HAVE_RES_INIT
71 #include <netinet/in.h>
72 #include <arpa/nameser.h>
73 #include <resolv.h>
74 #endif
75
76 #ifdef HAVE_UTIL_H
77 #include <util.h>
78 #endif
79
80 #ifdef HAVE_PTY_H
81 #include <pty.h>
82 #endif
83
84 #endif /* subprocesses */
85
86 #include "lisp.h"
87 #include "systime.h"
88 #include "systty.h"
89
90 #include "window.h"
91 #include "buffer.h"
92 #include "character.h"
93 #include "coding.h"
94 #include "process.h"
95 #include "frame.h"
96 #include "termhooks.h"
97 #include "termopts.h"
98 #include "commands.h"
99 #include "keyboard.h"
100 #include "blockinput.h"
101 #include "dispextern.h"
102 #include "composite.h"
103 #include "atimer.h"
104 #include "sysselect.h"
105 #include "syssignal.h"
106 #include "syswait.h"
107 #ifdef HAVE_GNUTLS
108 #include "gnutls.h"
109 #endif
110
111 #if defined (USE_GTK) || defined (HAVE_GCONF)
112 #include "xgselect.h"
113 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
114 #ifdef HAVE_NS
115 #include "nsterm.h"
116 #endif
117
118 extern int timers_run;
119
120 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
121 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
122 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
123 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
124 Lisp_Object QCname, QCtype;
125 \f
126 /* Non-zero if keyboard input is on hold, zero otherwise. */
127
128 static int kbd_is_on_hold;
129
130 /* Nonzero means delete a process right away if it exits. */
131 static int delete_exited_processes;
132
133 /* Nonzero means don't run process sentinels. This is used
134 when exiting. */
135 int inhibit_sentinels;
136
137 #ifdef subprocesses
138
139 Lisp_Object Qprocessp;
140 Lisp_Object Qrun, Qstop, Qsignal;
141 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
142 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
143 Lisp_Object Qreal, Qnetwork, Qserial;
144 #ifdef AF_INET6
145 Lisp_Object Qipv6;
146 #endif
147 Lisp_Object QCport, QCspeed, QCprocess;
148 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
149 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
150 Lisp_Object QCbuffer, QChost, QCservice;
151 Lisp_Object QClocal, QCremote, QCcoding;
152 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
153 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
154 Lisp_Object Qlast_nonmenu_event;
155 /* QCfamily is declared and initialized in xfaces.c,
156 QCfilter in keyboard.c. */
157 extern Lisp_Object QCfamily, QCfilter;
158
159 /* Qexit is declared and initialized in eval.c. */
160
161 /* QCfamily is defined in xfaces.c. */
162 extern Lisp_Object QCfamily;
163 /* QCfilter is defined in keyboard.c. */
164 extern Lisp_Object QCfilter;
165
166 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
167 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
168 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
169 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
170
171 /* Define first descriptor number available for subprocesses. */
172 #define FIRST_PROC_DESC 3
173
174 extern const char *get_operating_system_release (void);
175
176 /* From sysdep.c or w32.c */
177 extern int serial_open (char *port);
178 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
179
180 #ifndef HAVE_H_ERRNO
181 extern int h_errno;
182 #endif
183
184 /* t means use pty, nil means use a pipe,
185 maybe other values to come. */
186 static Lisp_Object Vprocess_connection_type;
187
188 /* These next two vars are non-static since sysdep.c uses them in the
189 emulation of `select'. */
190 /* Number of events of change of status of a process. */
191 int process_tick;
192 /* Number of events for which the user or sentinel has been notified. */
193 int update_tick;
194
195 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
196
197 /* Only W32 has this, it really means that select can't take write mask. */
198 #ifdef BROKEN_NON_BLOCKING_CONNECT
199 #undef NON_BLOCKING_CONNECT
200 #define SELECT_CANT_DO_WRITE_MASK
201 #else
202 #ifndef NON_BLOCKING_CONNECT
203 #ifdef HAVE_SELECT
204 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
205 #if defined (O_NONBLOCK) || defined (O_NDELAY)
206 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
207 #define NON_BLOCKING_CONNECT
208 #endif /* EWOULDBLOCK || EINPROGRESS */
209 #endif /* O_NONBLOCK || O_NDELAY */
210 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
211 #endif /* HAVE_SELECT */
212 #endif /* NON_BLOCKING_CONNECT */
213 #endif /* BROKEN_NON_BLOCKING_CONNECT */
214
215 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
216 this system. We need to read full packets, so we need a
217 "non-destructive" select. So we require either native select,
218 or emulation of select using FIONREAD. */
219
220 #ifdef BROKEN_DATAGRAM_SOCKETS
221 #undef DATAGRAM_SOCKETS
222 #else
223 #ifndef DATAGRAM_SOCKETS
224 #if defined (HAVE_SELECT) || defined (FIONREAD)
225 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
226 #define DATAGRAM_SOCKETS
227 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
228 #endif /* HAVE_SELECT || FIONREAD */
229 #endif /* DATAGRAM_SOCKETS */
230 #endif /* BROKEN_DATAGRAM_SOCKETS */
231
232 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
233 # define HAVE_SEQPACKET
234 #endif
235
236 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
237 #ifdef EMACS_HAS_USECS
238 #define ADAPTIVE_READ_BUFFERING
239 #endif
240 #endif
241
242 #ifdef ADAPTIVE_READ_BUFFERING
243 #define READ_OUTPUT_DELAY_INCREMENT 10000
244 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
245 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
246
247 /* Number of processes which have a non-zero read_output_delay,
248 and therefore might be delayed for adaptive read buffering. */
249
250 static int process_output_delay_count;
251
252 /* Non-zero if any process has non-nil read_output_skip. */
253
254 static int process_output_skip;
255
256 /* Non-nil means to delay reading process output to improve buffering.
257 A value of t means that delay is reset after each send, any other
258 non-nil value does not reset the delay. A value of nil disables
259 adaptive read buffering completely. */
260 static Lisp_Object Vprocess_adaptive_read_buffering;
261 #else
262 #define process_output_delay_count 0
263 #endif
264
265 static int keyboard_bit_set (SELECT_TYPE *);
266 static void deactivate_process (Lisp_Object);
267 static void status_notify (struct Lisp_Process *);
268 static int read_process_output (Lisp_Object, int);
269 static void create_pty (Lisp_Object);
270
271 /* If we support a window system, turn on the code to poll periodically
272 to detect C-g. It isn't actually used when doing interrupt input. */
273 #ifdef HAVE_WINDOW_SYSTEM
274 #define POLL_FOR_INPUT
275 #endif
276
277 static Lisp_Object get_process (register Lisp_Object name);
278 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
279
280 /* Mask of bits indicating the descriptors that we wait for input on. */
281
282 static SELECT_TYPE input_wait_mask;
283
284 /* Mask that excludes keyboard input descriptor(s). */
285
286 static SELECT_TYPE non_keyboard_wait_mask;
287
288 /* Mask that excludes process input descriptor(s). */
289
290 static SELECT_TYPE non_process_wait_mask;
291
292 /* Mask for selecting for write. */
293
294 static SELECT_TYPE write_mask;
295
296 #ifdef NON_BLOCKING_CONNECT
297 /* Mask of bits indicating the descriptors that we wait for connect to
298 complete on. Once they complete, they are removed from this mask
299 and added to the input_wait_mask and non_keyboard_wait_mask. */
300
301 static SELECT_TYPE connect_wait_mask;
302
303 /* Number of bits set in connect_wait_mask. */
304 static int num_pending_connects;
305
306 #define IF_NON_BLOCKING_CONNECT(s) s
307 #else /* NON_BLOCKING_CONNECT */
308 #define IF_NON_BLOCKING_CONNECT(s)
309 #endif /* NON_BLOCKING_CONNECT */
310
311 /* The largest descriptor currently in use for a process object. */
312 static int max_process_desc;
313
314 /* The largest descriptor currently in use for input. */
315 static int max_input_desc;
316
317 /* Indexed by descriptor, gives the process (if any) for that descriptor */
318 Lisp_Object chan_process[MAXDESC];
319
320 /* Alist of elements (NAME . PROCESS) */
321 Lisp_Object Vprocess_alist;
322
323 /* Buffered-ahead input char from process, indexed by channel.
324 -1 means empty (no char is buffered).
325 Used on sys V where the only way to tell if there is any
326 output from the process is to read at least one char.
327 Always -1 on systems that support FIONREAD. */
328
329 /* Don't make static; need to access externally. */
330 int proc_buffered_char[MAXDESC];
331
332 /* Table of `struct coding-system' for each process. */
333 static struct coding_system *proc_decode_coding_system[MAXDESC];
334 static struct coding_system *proc_encode_coding_system[MAXDESC];
335
336 #ifdef DATAGRAM_SOCKETS
337 /* Table of `partner address' for datagram sockets. */
338 struct sockaddr_and_len {
339 struct sockaddr *sa;
340 int len;
341 } datagram_address[MAXDESC];
342 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
343 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
344 #else
345 #define DATAGRAM_CHAN_P(chan) (0)
346 #define DATAGRAM_CONN_P(proc) (0)
347 #endif
348
349 /* Maximum number of bytes to send to a pty without an eof. */
350 static int pty_max_bytes;
351
352 \f
353
354 struct fd_callback_data
355 {
356 fd_callback func;
357 void *data;
358 #define FOR_READ 1
359 #define FOR_WRITE 2
360 int condition; /* mask of the defines above. */
361 } fd_callback_info[MAXDESC];
362
363
364 /* Add a file descriptor FD to be monitored for when read is possible.
365 When read is possible, call FUNC with argument DATA. */
366
367 void
368 add_read_fd (int fd, fd_callback func, void *data)
369 {
370 xassert (fd < MAXDESC);
371 add_keyboard_wait_descriptor (fd);
372
373 fd_callback_info[fd].func = func;
374 fd_callback_info[fd].data = data;
375 fd_callback_info[fd].condition |= FOR_READ;
376 }
377
378 /* Stop monitoring file descriptor FD for when read is possible. */
379
380 void
381 delete_read_fd (int fd)
382 {
383 xassert (fd < MAXDESC);
384 delete_keyboard_wait_descriptor (fd);
385
386 fd_callback_info[fd].condition &= ~FOR_READ;
387 if (fd_callback_info[fd].condition == 0)
388 {
389 fd_callback_info[fd].func = 0;
390 fd_callback_info[fd].data = 0;
391 }
392 }
393
394 /* Add a file descriptor FD to be monitored for when write is possible.
395 When write is possible, call FUNC with argument DATA. */
396
397 void
398 add_write_fd (int fd, fd_callback func, void *data)
399 {
400 xassert (fd < MAXDESC);
401 FD_SET (fd, &write_mask);
402 if (fd > max_input_desc)
403 max_input_desc = fd;
404
405 fd_callback_info[fd].func = func;
406 fd_callback_info[fd].data = data;
407 fd_callback_info[fd].condition |= FOR_WRITE;
408 }
409
410 /* Stop monitoring file descriptor FD for when write is possible. */
411
412 void
413 delete_write_fd (int fd)
414 {
415 int lim = max_input_desc;
416
417 xassert (fd < MAXDESC);
418 FD_CLR (fd, &write_mask);
419 fd_callback_info[fd].condition &= ~FOR_WRITE;
420 if (fd_callback_info[fd].condition == 0)
421 {
422 fd_callback_info[fd].func = 0;
423 fd_callback_info[fd].data = 0;
424
425 if (fd == max_input_desc)
426 for (fd = lim; fd >= 0; fd--)
427 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
428 {
429 max_input_desc = fd;
430 break;
431 }
432
433 }
434 }
435
436 \f
437 /* Compute the Lisp form of the process status, p->status, from
438 the numeric status that was returned by `wait'. */
439
440 static Lisp_Object status_convert (int);
441
442 static void
443 update_status (struct Lisp_Process *p)
444 {
445 eassert (p->raw_status_new);
446 p->status = status_convert (p->raw_status);
447 p->raw_status_new = 0;
448 }
449
450 /* Convert a process status word in Unix format to
451 the list that we use internally. */
452
453 static Lisp_Object
454 status_convert (int w)
455 {
456 if (WIFSTOPPED (w))
457 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
458 else if (WIFEXITED (w))
459 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
460 WCOREDUMP (w) ? Qt : Qnil));
461 else if (WIFSIGNALED (w))
462 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
463 WCOREDUMP (w) ? Qt : Qnil));
464 else
465 return Qrun;
466 }
467
468 /* Given a status-list, extract the three pieces of information
469 and store them individually through the three pointers. */
470
471 static void
472 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
473 {
474 Lisp_Object tem;
475
476 if (SYMBOLP (l))
477 {
478 *symbol = l;
479 *code = 0;
480 *coredump = 0;
481 }
482 else
483 {
484 *symbol = XCAR (l);
485 tem = XCDR (l);
486 *code = XFASTINT (XCAR (tem));
487 tem = XCDR (tem);
488 *coredump = !NILP (tem);
489 }
490 }
491
492 /* Return a string describing a process status list. */
493
494 static Lisp_Object
495 status_message (struct Lisp_Process *p)
496 {
497 Lisp_Object status = p->status;
498 Lisp_Object symbol;
499 int code, coredump;
500 Lisp_Object string, string2;
501
502 decode_status (status, &symbol, &code, &coredump);
503
504 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
505 {
506 char *signame;
507 synchronize_system_messages_locale ();
508 signame = strsignal (code);
509 if (signame == 0)
510 string = build_string ("unknown");
511 else
512 {
513 int c1, c2;
514
515 string = make_unibyte_string (signame, strlen (signame));
516 if (! NILP (Vlocale_coding_system))
517 string = (code_convert_string_norecord
518 (string, Vlocale_coding_system, 0));
519 c1 = STRING_CHAR ((char *) SDATA (string));
520 c2 = DOWNCASE (c1);
521 if (c1 != c2)
522 Faset (string, make_number (0), make_number (c2));
523 }
524 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
525 return concat2 (string, string2);
526 }
527 else if (EQ (symbol, Qexit))
528 {
529 if (NETCONN1_P (p))
530 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
531 if (code == 0)
532 return build_string ("finished\n");
533 string = Fnumber_to_string (make_number (code));
534 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
535 return concat3 (build_string ("exited abnormally with code "),
536 string, string2);
537 }
538 else if (EQ (symbol, Qfailed))
539 {
540 string = Fnumber_to_string (make_number (code));
541 string2 = build_string ("\n");
542 return concat3 (build_string ("failed with code "),
543 string, string2);
544 }
545 else
546 return Fcopy_sequence (Fsymbol_name (symbol));
547 }
548 \f
549 #ifdef HAVE_PTYS
550
551 /* The file name of the pty opened by allocate_pty. */
552 static char pty_name[24];
553
554 /* Open an available pty, returning a file descriptor.
555 Return -1 on failure.
556 The file name of the terminal corresponding to the pty
557 is left in the variable pty_name. */
558
559 static int
560 allocate_pty (void)
561 {
562 register int c, i;
563 int fd;
564
565 #ifdef PTY_ITERATION
566 PTY_ITERATION
567 #else
568 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
569 for (i = 0; i < 16; i++)
570 #endif
571 {
572 struct stat stb; /* Used in some PTY_OPEN. */
573 #ifdef PTY_NAME_SPRINTF
574 PTY_NAME_SPRINTF
575 #else
576 sprintf (pty_name, "/dev/pty%c%x", c, i);
577 #endif /* no PTY_NAME_SPRINTF */
578
579 #ifdef PTY_OPEN
580 PTY_OPEN;
581 #else /* no PTY_OPEN */
582 {
583 { /* Some systems name their pseudoterminals so that there are gaps in
584 the usual sequence - for example, on HP9000/S700 systems, there
585 are no pseudoterminals with names ending in 'f'. So we wait for
586 three failures in a row before deciding that we've reached the
587 end of the ptys. */
588 int failed_count = 0;
589
590 if (stat (pty_name, &stb) < 0)
591 {
592 failed_count++;
593 if (failed_count >= 3)
594 return -1;
595 }
596 else
597 failed_count = 0;
598 }
599 # ifdef O_NONBLOCK
600 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
601 # else
602 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
603 # endif
604 }
605 #endif /* no PTY_OPEN */
606
607 if (fd >= 0)
608 {
609 /* check to make certain that both sides are available
610 this avoids a nasty yet stupid bug in rlogins */
611 #ifdef PTY_TTY_NAME_SPRINTF
612 PTY_TTY_NAME_SPRINTF
613 #else
614 sprintf (pty_name, "/dev/tty%c%x", c, i);
615 #endif /* no PTY_TTY_NAME_SPRINTF */
616 if (access (pty_name, 6) != 0)
617 {
618 emacs_close (fd);
619 # ifndef __sgi
620 continue;
621 # else
622 return -1;
623 # endif /* __sgi */
624 }
625 setup_pty (fd);
626 return fd;
627 }
628 }
629 return -1;
630 }
631 #endif /* HAVE_PTYS */
632 \f
633 static Lisp_Object
634 make_process (Lisp_Object name)
635 {
636 register Lisp_Object val, tem, name1;
637 register struct Lisp_Process *p;
638 char suffix[10];
639 register int i;
640
641 p = allocate_process ();
642
643 p->infd = -1;
644 p->outfd = -1;
645 p->tick = 0;
646 p->update_tick = 0;
647 p->pid = 0;
648 p->pty_flag = 0;
649 p->raw_status_new = 0;
650 p->status = Qrun;
651 p->mark = Fmake_marker ();
652 p->kill_without_query = 0;
653
654 #ifdef ADAPTIVE_READ_BUFFERING
655 p->adaptive_read_buffering = 0;
656 p->read_output_delay = 0;
657 p->read_output_skip = 0;
658 #endif
659
660 #ifdef HAVE_GNUTLS
661 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
662 p->gnutls_log_level = 0;
663 p->gnutls_p = 0;
664 #endif
665
666 /* If name is already in use, modify it until it is unused. */
667
668 name1 = name;
669 for (i = 1; ; i++)
670 {
671 tem = Fget_process (name1);
672 if (NILP (tem)) break;
673 sprintf (suffix, "<%d>", i);
674 name1 = concat2 (name, build_string (suffix));
675 }
676 name = name1;
677 p->name = name;
678 XSETPROCESS (val, p);
679 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
680 return val;
681 }
682
683 static void
684 remove_process (register Lisp_Object proc)
685 {
686 register Lisp_Object pair;
687
688 pair = Frassq (proc, Vprocess_alist);
689 Vprocess_alist = Fdelq (pair, Vprocess_alist);
690
691 deactivate_process (proc);
692 }
693
694 \f
695 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
696 doc: /* Return t if OBJECT is a process. */)
697 (Lisp_Object object)
698 {
699 return PROCESSP (object) ? Qt : Qnil;
700 }
701
702 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
703 doc: /* Return the process named NAME, or nil if there is none. */)
704 (register Lisp_Object name)
705 {
706 if (PROCESSP (name))
707 return name;
708 CHECK_STRING (name);
709 return Fcdr (Fassoc (name, Vprocess_alist));
710 }
711
712 /* This is how commands for the user decode process arguments. It
713 accepts a process, a process name, a buffer, a buffer name, or nil.
714 Buffers denote the first process in the buffer, and nil denotes the
715 current buffer. */
716
717 static Lisp_Object
718 get_process (register Lisp_Object name)
719 {
720 register Lisp_Object proc, obj;
721 if (STRINGP (name))
722 {
723 obj = Fget_process (name);
724 if (NILP (obj))
725 obj = Fget_buffer (name);
726 if (NILP (obj))
727 error ("Process %s does not exist", SDATA (name));
728 }
729 else if (NILP (name))
730 obj = Fcurrent_buffer ();
731 else
732 obj = name;
733
734 /* Now obj should be either a buffer object or a process object.
735 */
736 if (BUFFERP (obj))
737 {
738 proc = Fget_buffer_process (obj);
739 if (NILP (proc))
740 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
741 }
742 else
743 {
744 CHECK_PROCESS (obj);
745 proc = obj;
746 }
747 return proc;
748 }
749
750
751 #ifdef SIGCHLD
752 /* Fdelete_process promises to immediately forget about the process, but in
753 reality, Emacs needs to remember those processes until they have been
754 treated by sigchld_handler; otherwise this handler would consider the
755 process as being synchronous and say that the synchronous process is
756 dead. */
757 static Lisp_Object deleted_pid_list;
758 #endif
759
760 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
761 doc: /* Delete PROCESS: kill it and forget about it immediately.
762 PROCESS may be a process, a buffer, the name of a process or buffer, or
763 nil, indicating the current buffer's process. */)
764 (register Lisp_Object process)
765 {
766 register struct Lisp_Process *p;
767
768 process = get_process (process);
769 p = XPROCESS (process);
770
771 p->raw_status_new = 0;
772 if (NETCONN1_P (p) || SERIALCONN1_P (p))
773 {
774 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
775 p->tick = ++process_tick;
776 status_notify (p);
777 redisplay_preserve_echo_area (13);
778 }
779 else if (p->infd >= 0)
780 {
781 #ifdef SIGCHLD
782 Lisp_Object symbol;
783 /* Assignment to EMACS_INT stops GCC whining about limited range
784 of data type. */
785 EMACS_INT pid = p->pid;
786
787 /* No problem storing the pid here, as it is still in Vprocess_alist. */
788 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
789 /* GC treated elements set to nil. */
790 Fdelq (Qnil, deleted_pid_list));
791 /* If the process has already signaled, remove it from the list. */
792 if (p->raw_status_new)
793 update_status (p);
794 symbol = p->status;
795 if (CONSP (p->status))
796 symbol = XCAR (p->status);
797 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
798 deleted_pid_list
799 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
800 else
801 #endif
802 {
803 Fkill_process (process, Qnil);
804 /* Do this now, since remove_process will make sigchld_handler do nothing. */
805 p->status
806 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
807 p->tick = ++process_tick;
808 status_notify (p);
809 redisplay_preserve_echo_area (13);
810 }
811 }
812 remove_process (process);
813 return Qnil;
814 }
815 \f
816 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
817 doc: /* Return the status of PROCESS.
818 The returned value is one of the following symbols:
819 run -- for a process that is running.
820 stop -- for a process stopped but continuable.
821 exit -- for a process that has exited.
822 signal -- for a process that has got a fatal signal.
823 open -- for a network stream connection that is open.
824 listen -- for a network stream server that is listening.
825 closed -- for a network stream connection that is closed.
826 connect -- when waiting for a non-blocking connection to complete.
827 failed -- when a non-blocking connection has failed.
828 nil -- if arg is a process name and no such process exists.
829 PROCESS may be a process, a buffer, the name of a process, or
830 nil, indicating the current buffer's process. */)
831 (register Lisp_Object process)
832 {
833 register struct Lisp_Process *p;
834 register Lisp_Object status;
835
836 if (STRINGP (process))
837 process = Fget_process (process);
838 else
839 process = get_process (process);
840
841 if (NILP (process))
842 return process;
843
844 p = XPROCESS (process);
845 if (p->raw_status_new)
846 update_status (p);
847 status = p->status;
848 if (CONSP (status))
849 status = XCAR (status);
850 if (NETCONN1_P (p) || SERIALCONN1_P (p))
851 {
852 if (EQ (status, Qexit))
853 status = Qclosed;
854 else if (EQ (p->command, Qt))
855 status = Qstop;
856 else if (EQ (status, Qrun))
857 status = Qopen;
858 }
859 return status;
860 }
861
862 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
863 1, 1, 0,
864 doc: /* Return the exit status of PROCESS or the signal number that killed it.
865 If PROCESS has not yet exited or died, return 0. */)
866 (register Lisp_Object process)
867 {
868 CHECK_PROCESS (process);
869 if (XPROCESS (process)->raw_status_new)
870 update_status (XPROCESS (process));
871 if (CONSP (XPROCESS (process)->status))
872 return XCAR (XCDR (XPROCESS (process)->status));
873 return make_number (0);
874 }
875
876 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
877 doc: /* Return the process id of PROCESS.
878 This is the pid of the external process which PROCESS uses or talks to.
879 For a network connection, this value is nil. */)
880 (register Lisp_Object process)
881 {
882 /* Assignment to EMACS_INT stops GCC whining about limited range of
883 data type. */
884 EMACS_INT pid;
885
886 CHECK_PROCESS (process);
887 pid = XPROCESS (process)->pid;
888 return (pid ? make_fixnum_or_float (pid) : Qnil);
889 }
890
891 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
892 doc: /* Return the name of PROCESS, as a string.
893 This is the name of the program invoked in PROCESS,
894 possibly modified to make it unique among process names. */)
895 (register Lisp_Object process)
896 {
897 CHECK_PROCESS (process);
898 return XPROCESS (process)->name;
899 }
900
901 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
902 doc: /* Return the command that was executed to start PROCESS.
903 This is a list of strings, the first string being the program executed
904 and the rest of the strings being the arguments given to it.
905 For a network or serial process, this is nil (process is running) or t
906 \(process is stopped). */)
907 (register Lisp_Object process)
908 {
909 CHECK_PROCESS (process);
910 return XPROCESS (process)->command;
911 }
912
913 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
914 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
915 This is the terminal that the process itself reads and writes on,
916 not the name of the pty that Emacs uses to talk with that terminal. */)
917 (register Lisp_Object process)
918 {
919 CHECK_PROCESS (process);
920 return XPROCESS (process)->tty_name;
921 }
922
923 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
924 2, 2, 0,
925 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
926 (register Lisp_Object process, Lisp_Object buffer)
927 {
928 struct Lisp_Process *p;
929
930 CHECK_PROCESS (process);
931 if (!NILP (buffer))
932 CHECK_BUFFER (buffer);
933 p = XPROCESS (process);
934 p->buffer = buffer;
935 if (NETCONN1_P (p) || SERIALCONN1_P (p))
936 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
937 setup_process_coding_systems (process);
938 return buffer;
939 }
940
941 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
942 1, 1, 0,
943 doc: /* Return the buffer PROCESS is associated with.
944 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
945 (register Lisp_Object process)
946 {
947 CHECK_PROCESS (process);
948 return XPROCESS (process)->buffer;
949 }
950
951 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
952 1, 1, 0,
953 doc: /* Return the marker for the end of the last output from PROCESS. */)
954 (register Lisp_Object process)
955 {
956 CHECK_PROCESS (process);
957 return XPROCESS (process)->mark;
958 }
959
960 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
961 2, 2, 0,
962 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
963 A value of t means stop accepting output from the process.
964
965 When a process has a filter, its buffer is not used for output.
966 Instead, each time it does output, the entire string of output is
967 passed to the filter.
968
969 The filter gets two arguments: the process and the string of output.
970 The string argument is normally a multibyte string, except:
971 - if the process' input coding system is no-conversion or raw-text,
972 it is a unibyte string (the non-converted input), or else
973 - if `default-enable-multibyte-characters' is nil, it is a unibyte
974 string (the result of converting the decoded input multibyte
975 string to unibyte with `string-make-unibyte'). */)
976 (register Lisp_Object process, Lisp_Object filter)
977 {
978 struct Lisp_Process *p;
979
980 CHECK_PROCESS (process);
981 p = XPROCESS (process);
982
983 /* Don't signal an error if the process' input file descriptor
984 is closed. This could make debugging Lisp more difficult,
985 for example when doing something like
986
987 (setq process (start-process ...))
988 (debug)
989 (set-process-filter process ...) */
990
991 if (p->infd >= 0)
992 {
993 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
994 {
995 FD_CLR (p->infd, &input_wait_mask);
996 FD_CLR (p->infd, &non_keyboard_wait_mask);
997 }
998 else if (EQ (p->filter, Qt)
999 /* Network or serial process not stopped: */
1000 && !EQ (p->command, Qt))
1001 {
1002 FD_SET (p->infd, &input_wait_mask);
1003 FD_SET (p->infd, &non_keyboard_wait_mask);
1004 }
1005 }
1006
1007 p->filter = filter;
1008 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1009 p->childp = Fplist_put (p->childp, QCfilter, filter);
1010 setup_process_coding_systems (process);
1011 return filter;
1012 }
1013
1014 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1015 1, 1, 0,
1016 doc: /* Returns the filter function of PROCESS; nil if none.
1017 See `set-process-filter' for more info on filter functions. */)
1018 (register Lisp_Object process)
1019 {
1020 CHECK_PROCESS (process);
1021 return XPROCESS (process)->filter;
1022 }
1023
1024 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1025 2, 2, 0,
1026 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1027 The sentinel is called as a function when the process changes state.
1028 It gets two arguments: the process, and a string describing the change. */)
1029 (register Lisp_Object process, Lisp_Object sentinel)
1030 {
1031 struct Lisp_Process *p;
1032
1033 CHECK_PROCESS (process);
1034 p = XPROCESS (process);
1035
1036 p->sentinel = sentinel;
1037 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1038 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1039 return sentinel;
1040 }
1041
1042 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1043 1, 1, 0,
1044 doc: /* Return the sentinel of PROCESS; nil if none.
1045 See `set-process-sentinel' for more info on sentinels. */)
1046 (register Lisp_Object process)
1047 {
1048 CHECK_PROCESS (process);
1049 return XPROCESS (process)->sentinel;
1050 }
1051
1052 DEFUN ("set-process-window-size", Fset_process_window_size,
1053 Sset_process_window_size, 3, 3, 0,
1054 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1055 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1056 {
1057 CHECK_PROCESS (process);
1058 CHECK_NATNUM (height);
1059 CHECK_NATNUM (width);
1060
1061 if (XPROCESS (process)->infd < 0
1062 || set_window_size (XPROCESS (process)->infd,
1063 XINT (height), XINT (width)) <= 0)
1064 return Qnil;
1065 else
1066 return Qt;
1067 }
1068
1069 DEFUN ("set-process-inherit-coding-system-flag",
1070 Fset_process_inherit_coding_system_flag,
1071 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1072 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1073 If the second argument FLAG is non-nil, then the variable
1074 `buffer-file-coding-system' of the buffer associated with PROCESS
1075 will be bound to the value of the coding system used to decode
1076 the process output.
1077
1078 This is useful when the coding system specified for the process buffer
1079 leaves either the character code conversion or the end-of-line conversion
1080 unspecified, or if the coding system used to decode the process output
1081 is more appropriate for saving the process buffer.
1082
1083 Binding the variable `inherit-process-coding-system' to non-nil before
1084 starting the process is an alternative way of setting the inherit flag
1085 for the process which will run. */)
1086 (register Lisp_Object process, Lisp_Object flag)
1087 {
1088 CHECK_PROCESS (process);
1089 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1090 return flag;
1091 }
1092
1093 DEFUN ("set-process-query-on-exit-flag",
1094 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1095 2, 2, 0,
1096 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1097 If the second argument FLAG is non-nil, Emacs will query the user before
1098 exiting or killing a buffer if PROCESS is running. */)
1099 (register Lisp_Object process, Lisp_Object flag)
1100 {
1101 CHECK_PROCESS (process);
1102 XPROCESS (process)->kill_without_query = NILP (flag);
1103 return flag;
1104 }
1105
1106 DEFUN ("process-query-on-exit-flag",
1107 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1108 1, 1, 0,
1109 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1110 (register Lisp_Object process)
1111 {
1112 CHECK_PROCESS (process);
1113 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1114 }
1115
1116 #ifdef DATAGRAM_SOCKETS
1117 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1118 #endif
1119
1120 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1121 1, 2, 0,
1122 doc: /* Return the contact info of PROCESS; t for a real child.
1123 For a network or serial connection, the value depends on the optional
1124 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1125 SERVICE) for a network connection or (PORT SPEED) for a serial
1126 connection. If KEY is t, the complete contact information for the
1127 connection is returned, else the specific value for the keyword KEY is
1128 returned. See `make-network-process' or `make-serial-process' for a
1129 list of keywords. */)
1130 (register Lisp_Object process, Lisp_Object key)
1131 {
1132 Lisp_Object contact;
1133
1134 CHECK_PROCESS (process);
1135 contact = XPROCESS (process)->childp;
1136
1137 #ifdef DATAGRAM_SOCKETS
1138 if (DATAGRAM_CONN_P (process)
1139 && (EQ (key, Qt) || EQ (key, QCremote)))
1140 contact = Fplist_put (contact, QCremote,
1141 Fprocess_datagram_address (process));
1142 #endif
1143
1144 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1145 return contact;
1146 if (NILP (key) && NETCONN_P (process))
1147 return Fcons (Fplist_get (contact, QChost),
1148 Fcons (Fplist_get (contact, QCservice), Qnil));
1149 if (NILP (key) && SERIALCONN_P (process))
1150 return Fcons (Fplist_get (contact, QCport),
1151 Fcons (Fplist_get (contact, QCspeed), Qnil));
1152 return Fplist_get (contact, key);
1153 }
1154
1155 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1156 1, 1, 0,
1157 doc: /* Return the plist of PROCESS. */)
1158 (register Lisp_Object process)
1159 {
1160 CHECK_PROCESS (process);
1161 return XPROCESS (process)->plist;
1162 }
1163
1164 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1165 2, 2, 0,
1166 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1167 (register Lisp_Object process, Lisp_Object plist)
1168 {
1169 CHECK_PROCESS (process);
1170 CHECK_LIST (plist);
1171
1172 XPROCESS (process)->plist = plist;
1173 return plist;
1174 }
1175
1176 #if 0 /* Turned off because we don't currently record this info
1177 in the process. Perhaps add it. */
1178 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1179 doc: /* Return the connection type of PROCESS.
1180 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1181 a socket connection. */)
1182 (Lisp_Object process)
1183 {
1184 return XPROCESS (process)->type;
1185 }
1186 #endif
1187
1188 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1189 doc: /* Return the connection type of PROCESS.
1190 The value is either the symbol `real', `network', or `serial'.
1191 PROCESS may be a process, a buffer, the name of a process or buffer, or
1192 nil, indicating the current buffer's process. */)
1193 (Lisp_Object process)
1194 {
1195 Lisp_Object proc;
1196 proc = get_process (process);
1197 return XPROCESS (proc)->type;
1198 }
1199
1200 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1201 1, 2, 0,
1202 doc: /* Convert network ADDRESS from internal format to a string.
1203 A 4 or 5 element vector represents an IPv4 address (with port number).
1204 An 8 or 9 element vector represents an IPv6 address (with port number).
1205 If optional second argument OMIT-PORT is non-nil, don't include a port
1206 number in the string, even when present in ADDRESS.
1207 Returns nil if format of ADDRESS is invalid. */)
1208 (Lisp_Object address, Lisp_Object omit_port)
1209 {
1210 if (NILP (address))
1211 return Qnil;
1212
1213 if (STRINGP (address)) /* AF_LOCAL */
1214 return address;
1215
1216 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1217 {
1218 register struct Lisp_Vector *p = XVECTOR (address);
1219 Lisp_Object args[10];
1220 int nargs, i;
1221
1222 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1223 {
1224 args[0] = build_string ("%d.%d.%d.%d");
1225 nargs = 4;
1226 }
1227 else if (p->size == 5)
1228 {
1229 args[0] = build_string ("%d.%d.%d.%d:%d");
1230 nargs = 5;
1231 }
1232 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1233 {
1234 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1235 nargs = 8;
1236 }
1237 else if (p->size == 9)
1238 {
1239 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1240 nargs = 9;
1241 }
1242 else
1243 return Qnil;
1244
1245 for (i = 0; i < nargs; i++)
1246 {
1247 EMACS_INT element = XINT (p->contents[i]);
1248
1249 if (element < 0 || element > 65535)
1250 return Qnil;
1251
1252 if (nargs <= 5 /* IPv4 */
1253 && i < 4 /* host, not port */
1254 && element > 255)
1255 return Qnil;
1256
1257 args[i+1] = p->contents[i];
1258 }
1259
1260 return Fformat (nargs+1, args);
1261 }
1262
1263 if (CONSP (address))
1264 {
1265 Lisp_Object args[2];
1266 args[0] = build_string ("<Family %d>");
1267 args[1] = Fcar (address);
1268 return Fformat (2, args);
1269 }
1270
1271 return Qnil;
1272 }
1273 \f
1274 static Lisp_Object
1275 list_processes_1 (Lisp_Object query_only)
1276 {
1277 register Lisp_Object tail, tem;
1278 Lisp_Object proc, minspace, tem1;
1279 register struct Lisp_Process *p;
1280 char tembuf[300];
1281 int w_proc, w_buffer, w_tty;
1282 int exited = 0;
1283 Lisp_Object i_status, i_buffer, i_tty, i_command;
1284
1285 w_proc = 4; /* Proc */
1286 w_buffer = 6; /* Buffer */
1287 w_tty = 0; /* Omit if no ttys */
1288
1289 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1290 {
1291 int i;
1292
1293 proc = Fcdr (XCAR (tail));
1294 p = XPROCESS (proc);
1295 if (NILP (p->type))
1296 continue;
1297 if (!NILP (query_only) && p->kill_without_query)
1298 continue;
1299 if (STRINGP (p->name)
1300 && ( i = SCHARS (p->name), (i > w_proc)))
1301 w_proc = i;
1302 if (!NILP (p->buffer))
1303 {
1304 if (NILP (XBUFFER (p->buffer)->name))
1305 {
1306 if (w_buffer < 8)
1307 w_buffer = 8; /* (Killed) */
1308 }
1309 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1310 w_buffer = i;
1311 }
1312 if (STRINGP (p->tty_name)
1313 && (i = SCHARS (p->tty_name), (i > w_tty)))
1314 w_tty = i;
1315 }
1316
1317 XSETFASTINT (i_status, w_proc + 1);
1318 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1319 if (w_tty)
1320 {
1321 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1322 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1323 }
1324 else
1325 {
1326 i_tty = Qnil;
1327 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1328 }
1329
1330 XSETFASTINT (minspace, 1);
1331
1332 set_buffer_internal (XBUFFER (Vstandard_output));
1333 current_buffer->undo_list = Qt;
1334
1335 current_buffer->truncate_lines = Qt;
1336
1337 write_string ("Proc", -1);
1338 Findent_to (i_status, minspace); write_string ("Status", -1);
1339 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1340 if (!NILP (i_tty))
1341 {
1342 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1343 }
1344 Findent_to (i_command, minspace); write_string ("Command", -1);
1345 write_string ("\n", -1);
1346
1347 write_string ("----", -1);
1348 Findent_to (i_status, minspace); write_string ("------", -1);
1349 Findent_to (i_buffer, minspace); write_string ("------", -1);
1350 if (!NILP (i_tty))
1351 {
1352 Findent_to (i_tty, minspace); write_string ("---", -1);
1353 }
1354 Findent_to (i_command, minspace); write_string ("-------", -1);
1355 write_string ("\n", -1);
1356
1357 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1358 {
1359 Lisp_Object symbol;
1360
1361 proc = Fcdr (XCAR (tail));
1362 p = XPROCESS (proc);
1363 if (NILP (p->type))
1364 continue;
1365 if (!NILP (query_only) && p->kill_without_query)
1366 continue;
1367
1368 Finsert (1, &p->name);
1369 Findent_to (i_status, minspace);
1370
1371 if (p->raw_status_new)
1372 update_status (p);
1373 symbol = p->status;
1374 if (CONSP (p->status))
1375 symbol = XCAR (p->status);
1376
1377 if (EQ (symbol, Qsignal))
1378 {
1379 Lisp_Object tem;
1380 tem = Fcar (Fcdr (p->status));
1381 Fprinc (symbol, Qnil);
1382 }
1383 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1384 {
1385 if (EQ (symbol, Qexit))
1386 write_string ("closed", -1);
1387 else if (EQ (p->command, Qt))
1388 write_string ("stopped", -1);
1389 else if (EQ (symbol, Qrun))
1390 write_string ("open", -1);
1391 else
1392 Fprinc (symbol, Qnil);
1393 }
1394 else if (SERIALCONN1_P (p))
1395 {
1396 write_string ("running", -1);
1397 }
1398 else
1399 Fprinc (symbol, Qnil);
1400
1401 if (EQ (symbol, Qexit))
1402 {
1403 Lisp_Object tem;
1404 tem = Fcar (Fcdr (p->status));
1405 if (XFASTINT (tem))
1406 {
1407 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1408 write_string (tembuf, -1);
1409 }
1410 }
1411
1412 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1413 exited++;
1414
1415 Findent_to (i_buffer, minspace);
1416 if (NILP (p->buffer))
1417 insert_string ("(none)");
1418 else if (NILP (XBUFFER (p->buffer)->name))
1419 insert_string ("(Killed)");
1420 else
1421 Finsert (1, &XBUFFER (p->buffer)->name);
1422
1423 if (!NILP (i_tty))
1424 {
1425 Findent_to (i_tty, minspace);
1426 if (STRINGP (p->tty_name))
1427 Finsert (1, &p->tty_name);
1428 }
1429
1430 Findent_to (i_command, minspace);
1431
1432 if (EQ (p->status, Qlisten))
1433 {
1434 Lisp_Object port = Fplist_get (p->childp, QCservice);
1435 if (INTEGERP (port))
1436 port = Fnumber_to_string (port);
1437 if (NILP (port))
1438 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1439 sprintf (tembuf, "(network %s server on %s)\n",
1440 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1441 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1442 insert_string (tembuf);
1443 }
1444 else if (NETCONN1_P (p))
1445 {
1446 /* For a local socket, there is no host name,
1447 so display service instead. */
1448 Lisp_Object host = Fplist_get (p->childp, QChost);
1449 if (!STRINGP (host))
1450 {
1451 host = Fplist_get (p->childp, QCservice);
1452 if (INTEGERP (host))
1453 host = Fnumber_to_string (host);
1454 }
1455 if (NILP (host))
1456 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1457 sprintf (tembuf, "(network %s connection to %s)\n",
1458 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1459 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1460 insert_string (tembuf);
1461 }
1462 else if (SERIALCONN1_P (p))
1463 {
1464 Lisp_Object port = Fplist_get (p->childp, QCport);
1465 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1466 insert_string ("(serial port ");
1467 if (STRINGP (port))
1468 insert_string (SDATA (port));
1469 else
1470 insert_string ("?");
1471 if (INTEGERP (speed))
1472 {
1473 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1474 insert_string (tembuf);
1475 }
1476 insert_string (")\n");
1477 }
1478 else
1479 {
1480 tem = p->command;
1481 while (1)
1482 {
1483 tem1 = Fcar (tem);
1484 if (NILP (tem1))
1485 break;
1486 Finsert (1, &tem1);
1487 tem = Fcdr (tem);
1488 if (NILP (tem))
1489 break;
1490 insert_string (" ");
1491 }
1492 insert_string ("\n");
1493 }
1494 }
1495 if (exited)
1496 {
1497 status_notify (NULL);
1498 redisplay_preserve_echo_area (13);
1499 }
1500 return Qnil;
1501 }
1502
1503 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1504 doc: /* Display a list of all processes.
1505 If optional argument QUERY-ONLY is non-nil, only processes with
1506 the query-on-exit flag set will be listed.
1507 Any process listed as exited or signaled is actually eliminated
1508 after the listing is made. */)
1509 (Lisp_Object query_only)
1510 {
1511 internal_with_output_to_temp_buffer ("*Process List*",
1512 list_processes_1, query_only);
1513 return Qnil;
1514 }
1515
1516 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1517 doc: /* Return a list of all processes. */)
1518 (void)
1519 {
1520 return Fmapcar (Qcdr, Vprocess_alist);
1521 }
1522 \f
1523 /* Starting asynchronous inferior processes. */
1524
1525 static Lisp_Object start_process_unwind (Lisp_Object proc);
1526
1527 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1528 doc: /* Start a program in a subprocess. Return the process object for it.
1529 NAME is name for process. It is modified if necessary to make it unique.
1530 BUFFER is the buffer (or buffer name) to associate with the process.
1531
1532 Process output (both standard output and standard error streams) goes
1533 at end of BUFFER, unless you specify an output stream or filter
1534 function to handle the output. BUFFER may also be nil, meaning that
1535 this process is not associated with any buffer.
1536
1537 PROGRAM is the program file name. It is searched for in PATH. If
1538 nil, just associate a pty with the buffer. Remaining arguments are
1539 strings to give program as arguments.
1540
1541 If you want to separate standard output from standard error, invoke
1542 the command through a shell and redirect one of them using the shell
1543 syntax.
1544
1545 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1546 (int nargs, register Lisp_Object *args)
1547 {
1548 Lisp_Object buffer, name, program, proc, current_dir, tem;
1549 register unsigned char **new_argv;
1550 register int i;
1551 int count = SPECPDL_INDEX ();
1552
1553 buffer = args[1];
1554 if (!NILP (buffer))
1555 buffer = Fget_buffer_create (buffer);
1556
1557 /* Make sure that the child will be able to chdir to the current
1558 buffer's current directory, or its unhandled equivalent. We
1559 can't just have the child check for an error when it does the
1560 chdir, since it's in a vfork.
1561
1562 We have to GCPRO around this because Fexpand_file_name and
1563 Funhandled_file_name_directory might call a file name handling
1564 function. The argument list is protected by the caller, so all
1565 we really have to worry about is buffer. */
1566 {
1567 struct gcpro gcpro1, gcpro2;
1568
1569 current_dir = current_buffer->directory;
1570
1571 GCPRO2 (buffer, current_dir);
1572
1573 current_dir = Funhandled_file_name_directory (current_dir);
1574 if (NILP (current_dir))
1575 /* If the file name handler says that current_dir is unreachable, use
1576 a sensible default. */
1577 current_dir = build_string ("~/");
1578 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1579 if (NILP (Ffile_accessible_directory_p (current_dir)))
1580 report_file_error ("Setting current directory",
1581 Fcons (current_buffer->directory, Qnil));
1582
1583 UNGCPRO;
1584 }
1585
1586 name = args[0];
1587 CHECK_STRING (name);
1588
1589 program = args[2];
1590
1591 if (!NILP (program))
1592 CHECK_STRING (program);
1593
1594 proc = make_process (name);
1595 /* If an error occurs and we can't start the process, we want to
1596 remove it from the process list. This means that each error
1597 check in create_process doesn't need to call remove_process
1598 itself; it's all taken care of here. */
1599 record_unwind_protect (start_process_unwind, proc);
1600
1601 XPROCESS (proc)->childp = Qt;
1602 XPROCESS (proc)->plist = Qnil;
1603 XPROCESS (proc)->type = Qreal;
1604 XPROCESS (proc)->buffer = buffer;
1605 XPROCESS (proc)->sentinel = Qnil;
1606 XPROCESS (proc)->filter = Qnil;
1607 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1608
1609 #ifdef HAVE_GNUTLS
1610 /* AKA GNUTLS_INITSTAGE(proc). */
1611 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1612 XPROCESS (proc)->gnutls_cred_type = Qnil;
1613 #endif
1614
1615 #ifdef ADAPTIVE_READ_BUFFERING
1616 XPROCESS (proc)->adaptive_read_buffering
1617 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1618 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1619 #endif
1620
1621 /* Make the process marker point into the process buffer (if any). */
1622 if (BUFFERP (buffer))
1623 set_marker_both (XPROCESS (proc)->mark, buffer,
1624 BUF_ZV (XBUFFER (buffer)),
1625 BUF_ZV_BYTE (XBUFFER (buffer)));
1626
1627 {
1628 /* Decide coding systems for communicating with the process. Here
1629 we don't setup the structure coding_system nor pay attention to
1630 unibyte mode. They are done in create_process. */
1631
1632 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1633 Lisp_Object coding_systems = Qt;
1634 Lisp_Object val, *args2;
1635 struct gcpro gcpro1, gcpro2;
1636
1637 val = Vcoding_system_for_read;
1638 if (NILP (val))
1639 {
1640 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1641 args2[0] = Qstart_process;
1642 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1643 GCPRO2 (proc, current_dir);
1644 if (!NILP (program))
1645 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1646 UNGCPRO;
1647 if (CONSP (coding_systems))
1648 val = XCAR (coding_systems);
1649 else if (CONSP (Vdefault_process_coding_system))
1650 val = XCAR (Vdefault_process_coding_system);
1651 }
1652 XPROCESS (proc)->decode_coding_system = val;
1653
1654 val = Vcoding_system_for_write;
1655 if (NILP (val))
1656 {
1657 if (EQ (coding_systems, Qt))
1658 {
1659 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1660 args2[0] = Qstart_process;
1661 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1662 GCPRO2 (proc, current_dir);
1663 if (!NILP (program))
1664 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1665 UNGCPRO;
1666 }
1667 if (CONSP (coding_systems))
1668 val = XCDR (coding_systems);
1669 else if (CONSP (Vdefault_process_coding_system))
1670 val = XCDR (Vdefault_process_coding_system);
1671 }
1672 XPROCESS (proc)->encode_coding_system = val;
1673 /* Note: At this momemnt, the above coding system may leave
1674 text-conversion or eol-conversion unspecified. They will be
1675 decided after we read output from the process and decode it by
1676 some coding system, or just before we actually send a text to
1677 the process. */
1678 }
1679
1680
1681 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1682 XPROCESS (proc)->decoding_carryover = 0;
1683 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1684
1685 XPROCESS (proc)->inherit_coding_system_flag
1686 = !(NILP (buffer) || !inherit_process_coding_system);
1687
1688 if (!NILP (program))
1689 {
1690 /* If program file name is not absolute, search our path for it.
1691 Put the name we will really use in TEM. */
1692 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1693 && !(SCHARS (program) > 1
1694 && IS_DEVICE_SEP (SREF (program, 1))))
1695 {
1696 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1697
1698 tem = Qnil;
1699 GCPRO4 (name, program, buffer, current_dir);
1700 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1701 UNGCPRO;
1702 if (NILP (tem))
1703 report_file_error ("Searching for program", Fcons (program, Qnil));
1704 tem = Fexpand_file_name (tem, Qnil);
1705 }
1706 else
1707 {
1708 if (!NILP (Ffile_directory_p (program)))
1709 error ("Specified program for new process is a directory");
1710 tem = program;
1711 }
1712
1713 /* If program file name starts with /: for quoting a magic name,
1714 discard that. */
1715 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1716 && SREF (tem, 1) == ':')
1717 tem = Fsubstring (tem, make_number (2), Qnil);
1718
1719 {
1720 Lisp_Object arg_encoding = Qnil;
1721 struct gcpro gcpro1;
1722 GCPRO1 (tem);
1723
1724 /* Encode the file name and put it in NEW_ARGV.
1725 That's where the child will use it to execute the program. */
1726 tem = Fcons (ENCODE_FILE (tem), Qnil);
1727
1728 /* Here we encode arguments by the coding system used for sending
1729 data to the process. We don't support using different coding
1730 systems for encoding arguments and for encoding data sent to the
1731 process. */
1732
1733 for (i = 3; i < nargs; i++)
1734 {
1735 tem = Fcons (args[i], tem);
1736 CHECK_STRING (XCAR (tem));
1737 if (STRING_MULTIBYTE (XCAR (tem)))
1738 {
1739 if (NILP (arg_encoding))
1740 arg_encoding = (complement_process_encoding_system
1741 (XPROCESS (proc)->encode_coding_system));
1742 XSETCAR (tem,
1743 code_convert_string_norecord
1744 (XCAR (tem), arg_encoding, 1));
1745 }
1746 }
1747
1748 UNGCPRO;
1749 }
1750
1751 /* Now that everything is encoded we can collect the strings into
1752 NEW_ARGV. */
1753 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1754 new_argv[nargs - 2] = 0;
1755
1756 for (i = nargs - 3; i >= 0; i--)
1757 {
1758 new_argv[i] = SDATA (XCAR (tem));
1759 tem = XCDR (tem);
1760 }
1761
1762 create_process (proc, (char **) new_argv, current_dir);
1763 }
1764 else
1765 create_pty (proc);
1766
1767 return unbind_to (count, proc);
1768 }
1769
1770 /* This function is the unwind_protect form for Fstart_process. If
1771 PROC doesn't have its pid set, then we know someone has signaled
1772 an error and the process wasn't started successfully, so we should
1773 remove it from the process list. */
1774 static Lisp_Object
1775 start_process_unwind (Lisp_Object proc)
1776 {
1777 if (!PROCESSP (proc))
1778 abort ();
1779
1780 /* Was PROC started successfully? */
1781 if (XPROCESS (proc)->pid == -1)
1782 remove_process (proc);
1783
1784 return Qnil;
1785 }
1786
1787 static void
1788 create_process_1 (struct atimer *timer)
1789 {
1790 /* Nothing to do. */
1791 }
1792
1793
1794 void
1795 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1796 {
1797 int inchannel, outchannel;
1798 pid_t pid;
1799 int sv[2];
1800 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1801 int wait_child_setup[2];
1802 #endif
1803 sigset_t procmask;
1804 sigset_t blocked;
1805 struct sigaction sigint_action;
1806 struct sigaction sigquit_action;
1807 #ifdef AIX
1808 struct sigaction sighup_action;
1809 #endif
1810 /* Use volatile to protect variables from being clobbered by longjmp. */
1811 volatile int forkin, forkout;
1812 volatile int pty_flag = 0;
1813 #ifndef USE_CRT_DLL
1814 extern char **environ;
1815 #endif
1816
1817 inchannel = outchannel = -1;
1818
1819 #ifdef HAVE_PTYS
1820 if (!NILP (Vprocess_connection_type))
1821 outchannel = inchannel = allocate_pty ();
1822
1823 if (inchannel >= 0)
1824 {
1825 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1826 /* On most USG systems it does not work to open the pty's tty here,
1827 then close it and reopen it in the child. */
1828 #ifdef O_NOCTTY
1829 /* Don't let this terminal become our controlling terminal
1830 (in case we don't have one). */
1831 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1832 #else
1833 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1834 #endif
1835 if (forkin < 0)
1836 report_file_error ("Opening pty", Qnil);
1837 #else
1838 forkin = forkout = -1;
1839 #endif /* not USG, or USG_SUBTTY_WORKS */
1840 pty_flag = 1;
1841 }
1842 else
1843 #endif /* HAVE_PTYS */
1844 {
1845 int tem;
1846 tem = pipe (sv);
1847 if (tem < 0)
1848 report_file_error ("Creating pipe", Qnil);
1849 inchannel = sv[0];
1850 forkout = sv[1];
1851 tem = pipe (sv);
1852 if (tem < 0)
1853 {
1854 emacs_close (inchannel);
1855 emacs_close (forkout);
1856 report_file_error ("Creating pipe", Qnil);
1857 }
1858 outchannel = sv[1];
1859 forkin = sv[0];
1860 }
1861
1862 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1863 {
1864 int tem;
1865
1866 tem = pipe (wait_child_setup);
1867 if (tem < 0)
1868 report_file_error ("Creating pipe", Qnil);
1869 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1870 if (tem >= 0)
1871 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1872 if (tem < 0)
1873 {
1874 emacs_close (wait_child_setup[0]);
1875 emacs_close (wait_child_setup[1]);
1876 report_file_error ("Setting file descriptor flags", Qnil);
1877 }
1878 }
1879 #endif
1880
1881 #ifdef O_NONBLOCK
1882 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1883 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1884 #else
1885 #ifdef O_NDELAY
1886 fcntl (inchannel, F_SETFL, O_NDELAY);
1887 fcntl (outchannel, F_SETFL, O_NDELAY);
1888 #endif
1889 #endif
1890
1891 /* Record this as an active process, with its channels.
1892 As a result, child_setup will close Emacs's side of the pipes. */
1893 chan_process[inchannel] = process;
1894 XPROCESS (process)->infd = inchannel;
1895 XPROCESS (process)->outfd = outchannel;
1896
1897 /* Previously we recorded the tty descriptor used in the subprocess.
1898 It was only used for getting the foreground tty process, so now
1899 we just reopen the device (see emacs_get_tty_pgrp) as this is
1900 more portable (see USG_SUBTTY_WORKS above). */
1901
1902 XPROCESS (process)->pty_flag = pty_flag;
1903 XPROCESS (process)->status = Qrun;
1904 setup_process_coding_systems (process);
1905
1906 /* Delay interrupts until we have a chance to store
1907 the new fork's pid in its process structure */
1908 sigemptyset (&blocked);
1909 #ifdef SIGCHLD
1910 sigaddset (&blocked, SIGCHLD);
1911 #endif
1912 #ifdef HAVE_WORKING_VFORK
1913 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1914 this sets the parent's signal handlers as well as the child's.
1915 So delay all interrupts whose handlers the child might munge,
1916 and record the current handlers so they can be restored later. */
1917 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1918 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1919 #ifdef AIX
1920 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1921 #endif
1922 #endif /* HAVE_WORKING_VFORK */
1923 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1924
1925 FD_SET (inchannel, &input_wait_mask);
1926 FD_SET (inchannel, &non_keyboard_wait_mask);
1927 if (inchannel > max_process_desc)
1928 max_process_desc = inchannel;
1929
1930 /* Until we store the proper pid, enable sigchld_handler
1931 to recognize an unknown pid as standing for this process.
1932 It is very important not to let this `marker' value stay
1933 in the table after this function has returned; if it does
1934 it might cause call-process to hang and subsequent asynchronous
1935 processes to get their return values scrambled. */
1936 XPROCESS (process)->pid = -1;
1937
1938 BLOCK_INPUT;
1939
1940 {
1941 /* child_setup must clobber environ on systems with true vfork.
1942 Protect it from permanent change. */
1943 char **save_environ = environ;
1944
1945 current_dir = ENCODE_FILE (current_dir);
1946
1947 #ifndef WINDOWSNT
1948 pid = vfork ();
1949 if (pid == 0)
1950 #endif /* not WINDOWSNT */
1951 {
1952 int xforkin = forkin;
1953 int xforkout = forkout;
1954
1955 #if 0 /* This was probably a mistake--it duplicates code later on,
1956 but fails to handle all the cases. */
1957 /* Make sure SIGCHLD is not blocked in the child. */
1958 sigsetmask (SIGEMPTYMASK);
1959 #endif
1960
1961 /* Make the pty be the controlling terminal of the process. */
1962 #ifdef HAVE_PTYS
1963 /* First, disconnect its current controlling terminal. */
1964 #ifdef HAVE_SETSID
1965 /* We tried doing setsid only if pty_flag, but it caused
1966 process_set_signal to fail on SGI when using a pipe. */
1967 setsid ();
1968 /* Make the pty's terminal the controlling terminal. */
1969 if (pty_flag && xforkin >= 0)
1970 {
1971 #ifdef TIOCSCTTY
1972 /* We ignore the return value
1973 because faith@cs.unc.edu says that is necessary on Linux. */
1974 ioctl (xforkin, TIOCSCTTY, 0);
1975 #endif
1976 }
1977 #else /* not HAVE_SETSID */
1978 #ifdef USG
1979 /* It's very important to call setpgrp here and no time
1980 afterwards. Otherwise, we lose our controlling tty which
1981 is set when we open the pty. */
1982 setpgrp ();
1983 #endif /* USG */
1984 #endif /* not HAVE_SETSID */
1985 #if defined (LDISC1)
1986 if (pty_flag && xforkin >= 0)
1987 {
1988 struct termios t;
1989 tcgetattr (xforkin, &t);
1990 t.c_lflag = LDISC1;
1991 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1992 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1993 }
1994 #else
1995 #if defined (NTTYDISC) && defined (TIOCSETD)
1996 if (pty_flag && xforkin >= 0)
1997 {
1998 /* Use new line discipline. */
1999 int ldisc = NTTYDISC;
2000 ioctl (xforkin, TIOCSETD, &ldisc);
2001 }
2002 #endif
2003 #endif
2004 #ifdef TIOCNOTTY
2005 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2006 can do TIOCSPGRP only to the process's controlling tty. */
2007 if (pty_flag)
2008 {
2009 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2010 I can't test it since I don't have 4.3. */
2011 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2012 if (j >= 0)
2013 {
2014 ioctl (j, TIOCNOTTY, 0);
2015 emacs_close (j);
2016 }
2017 #ifndef USG
2018 /* In order to get a controlling terminal on some versions
2019 of BSD, it is necessary to put the process in pgrp 0
2020 before it opens the terminal. */
2021 #ifdef HAVE_SETPGID
2022 setpgid (0, 0);
2023 #else
2024 setpgrp (0, 0);
2025 #endif
2026 #endif
2027 }
2028 #endif /* TIOCNOTTY */
2029
2030 #if !defined (DONT_REOPEN_PTY)
2031 /*** There is a suggestion that this ought to be a
2032 conditional on TIOCSPGRP,
2033 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2034 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2035 that system does seem to need this code, even though
2036 both HAVE_SETSID and TIOCSCTTY are defined. */
2037 /* Now close the pty (if we had it open) and reopen it.
2038 This makes the pty the controlling terminal of the subprocess. */
2039 if (pty_flag)
2040 {
2041
2042 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2043 would work? */
2044 if (xforkin >= 0)
2045 emacs_close (xforkin);
2046 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2047
2048 if (xforkin < 0)
2049 {
2050 emacs_write (1, "Couldn't open the pty terminal ", 31);
2051 emacs_write (1, pty_name, strlen (pty_name));
2052 emacs_write (1, "\n", 1);
2053 _exit (1);
2054 }
2055
2056 }
2057 #endif /* not DONT_REOPEN_PTY */
2058
2059 #ifdef SETUP_SLAVE_PTY
2060 if (pty_flag)
2061 {
2062 SETUP_SLAVE_PTY;
2063 }
2064 #endif /* SETUP_SLAVE_PTY */
2065 #ifdef AIX
2066 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2067 Now reenable it in the child, so it will die when we want it to. */
2068 if (pty_flag)
2069 signal (SIGHUP, SIG_DFL);
2070 #endif
2071 #endif /* HAVE_PTYS */
2072
2073 signal (SIGINT, SIG_DFL);
2074 signal (SIGQUIT, SIG_DFL);
2075
2076 /* Stop blocking signals in the child. */
2077 sigprocmask (SIG_SETMASK, &procmask, 0);
2078
2079 if (pty_flag)
2080 child_setup_tty (xforkout);
2081 #ifdef WINDOWSNT
2082 pid = child_setup (xforkin, xforkout, xforkout,
2083 new_argv, 1, current_dir);
2084 #else /* not WINDOWSNT */
2085 #ifdef FD_CLOEXEC
2086 emacs_close (wait_child_setup[0]);
2087 #endif
2088 child_setup (xforkin, xforkout, xforkout,
2089 new_argv, 1, current_dir);
2090 #endif /* not WINDOWSNT */
2091 }
2092 environ = save_environ;
2093 }
2094
2095 UNBLOCK_INPUT;
2096
2097 /* This runs in the Emacs process. */
2098 if (pid < 0)
2099 {
2100 if (forkin >= 0)
2101 emacs_close (forkin);
2102 if (forkin != forkout && forkout >= 0)
2103 emacs_close (forkout);
2104 }
2105 else
2106 {
2107 /* vfork succeeded. */
2108 XPROCESS (process)->pid = pid;
2109
2110 #ifdef WINDOWSNT
2111 register_child (pid, inchannel);
2112 #endif /* WINDOWSNT */
2113
2114 /* If the subfork execv fails, and it exits,
2115 this close hangs. I don't know why.
2116 So have an interrupt jar it loose. */
2117 {
2118 struct atimer *timer;
2119 EMACS_TIME offset;
2120
2121 stop_polling ();
2122 EMACS_SET_SECS_USECS (offset, 1, 0);
2123 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2124
2125 if (forkin >= 0)
2126 emacs_close (forkin);
2127
2128 cancel_atimer (timer);
2129 start_polling ();
2130 }
2131
2132 if (forkin != forkout && forkout >= 0)
2133 emacs_close (forkout);
2134
2135 #ifdef HAVE_PTYS
2136 if (pty_flag)
2137 XPROCESS (process)->tty_name = build_string (pty_name);
2138 else
2139 #endif
2140 XPROCESS (process)->tty_name = Qnil;
2141
2142 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2143 /* Wait for child_setup to complete in case that vfork is
2144 actually defined as fork. The descriptor wait_child_setup[1]
2145 of a pipe is closed at the child side either by close-on-exec
2146 on successful execvp or the _exit call in child_setup. */
2147 {
2148 char dummy;
2149
2150 emacs_close (wait_child_setup[1]);
2151 emacs_read (wait_child_setup[0], &dummy, 1);
2152 emacs_close (wait_child_setup[0]);
2153 }
2154 #endif
2155 }
2156
2157 /* Restore the signal state whether vfork succeeded or not.
2158 (We will signal an error, below, if it failed.) */
2159 #ifdef HAVE_WORKING_VFORK
2160 /* Restore the parent's signal handlers. */
2161 sigaction (SIGINT, &sigint_action, 0);
2162 sigaction (SIGQUIT, &sigquit_action, 0);
2163 #ifdef AIX
2164 sigaction (SIGHUP, &sighup_action, 0);
2165 #endif
2166 #endif /* HAVE_WORKING_VFORK */
2167 /* Stop blocking signals in the parent. */
2168 sigprocmask (SIG_SETMASK, &procmask, 0);
2169
2170 /* Now generate the error if vfork failed. */
2171 if (pid < 0)
2172 report_file_error ("Doing vfork", Qnil);
2173 }
2174
2175 void
2176 create_pty (Lisp_Object process)
2177 {
2178 int inchannel, outchannel;
2179
2180 /* Use volatile to protect variables from being clobbered by longjmp. */
2181 volatile int forkin, forkout;
2182 volatile int pty_flag = 0;
2183
2184 inchannel = outchannel = -1;
2185
2186 #ifdef HAVE_PTYS
2187 if (!NILP (Vprocess_connection_type))
2188 outchannel = inchannel = allocate_pty ();
2189
2190 if (inchannel >= 0)
2191 {
2192 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2193 /* On most USG systems it does not work to open the pty's tty here,
2194 then close it and reopen it in the child. */
2195 #ifdef O_NOCTTY
2196 /* Don't let this terminal become our controlling terminal
2197 (in case we don't have one). */
2198 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2199 #else
2200 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2201 #endif
2202 if (forkin < 0)
2203 report_file_error ("Opening pty", Qnil);
2204 #if defined (DONT_REOPEN_PTY)
2205 /* In the case that vfork is defined as fork, the parent process
2206 (Emacs) may send some data before the child process completes
2207 tty options setup. So we setup tty before forking. */
2208 child_setup_tty (forkout);
2209 #endif /* DONT_REOPEN_PTY */
2210 #else
2211 forkin = forkout = -1;
2212 #endif /* not USG, or USG_SUBTTY_WORKS */
2213 pty_flag = 1;
2214 }
2215 #endif /* HAVE_PTYS */
2216
2217 #ifdef O_NONBLOCK
2218 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2219 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2220 #else
2221 #ifdef O_NDELAY
2222 fcntl (inchannel, F_SETFL, O_NDELAY);
2223 fcntl (outchannel, F_SETFL, O_NDELAY);
2224 #endif
2225 #endif
2226
2227 /* Record this as an active process, with its channels.
2228 As a result, child_setup will close Emacs's side of the pipes. */
2229 chan_process[inchannel] = process;
2230 XPROCESS (process)->infd = inchannel;
2231 XPROCESS (process)->outfd = outchannel;
2232
2233 /* Previously we recorded the tty descriptor used in the subprocess.
2234 It was only used for getting the foreground tty process, so now
2235 we just reopen the device (see emacs_get_tty_pgrp) as this is
2236 more portable (see USG_SUBTTY_WORKS above). */
2237
2238 XPROCESS (process)->pty_flag = pty_flag;
2239 XPROCESS (process)->status = Qrun;
2240 setup_process_coding_systems (process);
2241
2242 FD_SET (inchannel, &input_wait_mask);
2243 FD_SET (inchannel, &non_keyboard_wait_mask);
2244 if (inchannel > max_process_desc)
2245 max_process_desc = inchannel;
2246
2247 XPROCESS (process)->pid = -2;
2248 #ifdef HAVE_PTYS
2249 if (pty_flag)
2250 XPROCESS (process)->tty_name = build_string (pty_name);
2251 else
2252 #endif
2253 XPROCESS (process)->tty_name = Qnil;
2254 }
2255
2256 \f
2257 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2258 The address family of sa is not included in the result. */
2259
2260 static Lisp_Object
2261 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2262 {
2263 Lisp_Object address;
2264 int i;
2265 unsigned char *cp;
2266 register struct Lisp_Vector *p;
2267
2268 /* Workaround for a bug in getsockname on BSD: Names bound to
2269 sockets in the UNIX domain are inaccessible; getsockname returns
2270 a zero length name. */
2271 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2272 return empty_unibyte_string;
2273
2274 switch (sa->sa_family)
2275 {
2276 case AF_INET:
2277 {
2278 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2279 len = sizeof (sin->sin_addr) + 1;
2280 address = Fmake_vector (make_number (len), Qnil);
2281 p = XVECTOR (address);
2282 p->contents[--len] = make_number (ntohs (sin->sin_port));
2283 cp = (unsigned char *) &sin->sin_addr;
2284 break;
2285 }
2286 #ifdef AF_INET6
2287 case AF_INET6:
2288 {
2289 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2290 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2291 len = sizeof (sin6->sin6_addr)/2 + 1;
2292 address = Fmake_vector (make_number (len), Qnil);
2293 p = XVECTOR (address);
2294 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2295 for (i = 0; i < len; i++)
2296 p->contents[i] = make_number (ntohs (ip6[i]));
2297 return address;
2298 }
2299 #endif
2300 #ifdef HAVE_LOCAL_SOCKETS
2301 case AF_LOCAL:
2302 {
2303 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2304 for (i = 0; i < sizeof (sockun->sun_path); i++)
2305 if (sockun->sun_path[i] == 0)
2306 break;
2307 return make_unibyte_string (sockun->sun_path, i);
2308 }
2309 #endif
2310 default:
2311 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2312 address = Fcons (make_number (sa->sa_family),
2313 Fmake_vector (make_number (len), Qnil));
2314 p = XVECTOR (XCDR (address));
2315 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2316 break;
2317 }
2318
2319 i = 0;
2320 while (i < len)
2321 p->contents[i++] = make_number (*cp++);
2322
2323 return address;
2324 }
2325
2326
2327 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2328
2329 static int
2330 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2331 {
2332 register struct Lisp_Vector *p;
2333
2334 if (VECTORP (address))
2335 {
2336 p = XVECTOR (address);
2337 if (p->size == 5)
2338 {
2339 *familyp = AF_INET;
2340 return sizeof (struct sockaddr_in);
2341 }
2342 #ifdef AF_INET6
2343 else if (p->size == 9)
2344 {
2345 *familyp = AF_INET6;
2346 return sizeof (struct sockaddr_in6);
2347 }
2348 #endif
2349 }
2350 #ifdef HAVE_LOCAL_SOCKETS
2351 else if (STRINGP (address))
2352 {
2353 *familyp = AF_LOCAL;
2354 return sizeof (struct sockaddr_un);
2355 }
2356 #endif
2357 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2358 {
2359 struct sockaddr *sa;
2360 *familyp = XINT (XCAR (address));
2361 p = XVECTOR (XCDR (address));
2362 return p->size + sizeof (sa->sa_family);
2363 }
2364 return 0;
2365 }
2366
2367 /* Convert an address object (vector or string) to an internal sockaddr.
2368
2369 The address format has been basically validated by
2370 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2371 it could have come from user data. So if FAMILY is not valid,
2372 we return after zeroing *SA. */
2373
2374 static void
2375 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2376 {
2377 register struct Lisp_Vector *p;
2378 register unsigned char *cp = NULL;
2379 register int i;
2380
2381 memset (sa, 0, len);
2382
2383 if (VECTORP (address))
2384 {
2385 p = XVECTOR (address);
2386 if (family == AF_INET)
2387 {
2388 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2389 len = sizeof (sin->sin_addr) + 1;
2390 i = XINT (p->contents[--len]);
2391 sin->sin_port = htons (i);
2392 cp = (unsigned char *)&sin->sin_addr;
2393 sa->sa_family = family;
2394 }
2395 #ifdef AF_INET6
2396 else if (family == AF_INET6)
2397 {
2398 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2399 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2400 len = sizeof (sin6->sin6_addr) + 1;
2401 i = XINT (p->contents[--len]);
2402 sin6->sin6_port = htons (i);
2403 for (i = 0; i < len; i++)
2404 if (INTEGERP (p->contents[i]))
2405 {
2406 int j = XFASTINT (p->contents[i]) & 0xffff;
2407 ip6[i] = ntohs (j);
2408 }
2409 sa->sa_family = family;
2410 return;
2411 }
2412 #endif
2413 else
2414 return;
2415 }
2416 else if (STRINGP (address))
2417 {
2418 #ifdef HAVE_LOCAL_SOCKETS
2419 if (family == AF_LOCAL)
2420 {
2421 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2422 cp = SDATA (address);
2423 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2424 sockun->sun_path[i] = *cp++;
2425 sa->sa_family = family;
2426 }
2427 #endif
2428 return;
2429 }
2430 else
2431 {
2432 p = XVECTOR (XCDR (address));
2433 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2434 }
2435
2436 for (i = 0; i < len; i++)
2437 if (INTEGERP (p->contents[i]))
2438 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2439 }
2440
2441 #ifdef DATAGRAM_SOCKETS
2442 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2443 1, 1, 0,
2444 doc: /* Get the current datagram address associated with PROCESS. */)
2445 (Lisp_Object process)
2446 {
2447 int channel;
2448
2449 CHECK_PROCESS (process);
2450
2451 if (!DATAGRAM_CONN_P (process))
2452 return Qnil;
2453
2454 channel = XPROCESS (process)->infd;
2455 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2456 datagram_address[channel].len);
2457 }
2458
2459 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2460 2, 2, 0,
2461 doc: /* Set the datagram address for PROCESS to ADDRESS.
2462 Returns nil upon error setting address, ADDRESS otherwise. */)
2463 (Lisp_Object process, Lisp_Object address)
2464 {
2465 int channel;
2466 int family, len;
2467
2468 CHECK_PROCESS (process);
2469
2470 if (!DATAGRAM_CONN_P (process))
2471 return Qnil;
2472
2473 channel = XPROCESS (process)->infd;
2474
2475 len = get_lisp_to_sockaddr_size (address, &family);
2476 if (datagram_address[channel].len != len)
2477 return Qnil;
2478 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2479 return address;
2480 }
2481 #endif
2482 \f
2483
2484 static const struct socket_options {
2485 /* The name of this option. Should be lowercase version of option
2486 name without SO_ prefix. */
2487 const char *name;
2488 /* Option level SOL_... */
2489 int optlevel;
2490 /* Option number SO_... */
2491 int optnum;
2492 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2493 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2494 } socket_options[] =
2495 {
2496 #ifdef SO_BINDTODEVICE
2497 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2498 #endif
2499 #ifdef SO_BROADCAST
2500 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2501 #endif
2502 #ifdef SO_DONTROUTE
2503 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2504 #endif
2505 #ifdef SO_KEEPALIVE
2506 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2507 #endif
2508 #ifdef SO_LINGER
2509 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2510 #endif
2511 #ifdef SO_OOBINLINE
2512 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2513 #endif
2514 #ifdef SO_PRIORITY
2515 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2516 #endif
2517 #ifdef SO_REUSEADDR
2518 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2519 #endif
2520 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2521 };
2522
2523 /* Set option OPT to value VAL on socket S.
2524
2525 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2526 Signals an error if setting a known option fails.
2527 */
2528
2529 static int
2530 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2531 {
2532 char *name;
2533 const struct socket_options *sopt;
2534 int ret = 0;
2535
2536 CHECK_SYMBOL (opt);
2537
2538 name = (char *) SDATA (SYMBOL_NAME (opt));
2539 for (sopt = socket_options; sopt->name; sopt++)
2540 if (strcmp (name, sopt->name) == 0)
2541 break;
2542
2543 switch (sopt->opttype)
2544 {
2545 case SOPT_BOOL:
2546 {
2547 int optval;
2548 optval = NILP (val) ? 0 : 1;
2549 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2550 &optval, sizeof (optval));
2551 break;
2552 }
2553
2554 case SOPT_INT:
2555 {
2556 int optval;
2557 if (INTEGERP (val))
2558 optval = XINT (val);
2559 else
2560 error ("Bad option value for %s", name);
2561 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2562 &optval, sizeof (optval));
2563 break;
2564 }
2565
2566 #ifdef SO_BINDTODEVICE
2567 case SOPT_IFNAME:
2568 {
2569 char devname[IFNAMSIZ+1];
2570
2571 /* This is broken, at least in the Linux 2.4 kernel.
2572 To unbind, the arg must be a zero integer, not the empty string.
2573 This should work on all systems. KFS. 2003-09-23. */
2574 memset (devname, 0, sizeof devname);
2575 if (STRINGP (val))
2576 {
2577 char *arg = (char *) SDATA (val);
2578 int len = min (strlen (arg), IFNAMSIZ);
2579 memcpy (devname, arg, len);
2580 }
2581 else if (!NILP (val))
2582 error ("Bad option value for %s", name);
2583 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2584 devname, IFNAMSIZ);
2585 break;
2586 }
2587 #endif
2588
2589 #ifdef SO_LINGER
2590 case SOPT_LINGER:
2591 {
2592 struct linger linger;
2593
2594 linger.l_onoff = 1;
2595 linger.l_linger = 0;
2596 if (INTEGERP (val))
2597 linger.l_linger = XINT (val);
2598 else
2599 linger.l_onoff = NILP (val) ? 0 : 1;
2600 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2601 &linger, sizeof (linger));
2602 break;
2603 }
2604 #endif
2605
2606 default:
2607 return 0;
2608 }
2609
2610 if (ret < 0)
2611 report_file_error ("Cannot set network option",
2612 Fcons (opt, Fcons (val, Qnil)));
2613 return (1 << sopt->optbit);
2614 }
2615
2616
2617 DEFUN ("set-network-process-option",
2618 Fset_network_process_option, Sset_network_process_option,
2619 3, 4, 0,
2620 doc: /* For network process PROCESS set option OPTION to value VALUE.
2621 See `make-network-process' for a list of options and values.
2622 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2623 OPTION is not a supported option, return nil instead; otherwise return t. */)
2624 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2625 {
2626 int s;
2627 struct Lisp_Process *p;
2628
2629 CHECK_PROCESS (process);
2630 p = XPROCESS (process);
2631 if (!NETCONN1_P (p))
2632 error ("Process is not a network process");
2633
2634 s = p->infd;
2635 if (s < 0)
2636 error ("Process is not running");
2637
2638 if (set_socket_option (s, option, value))
2639 {
2640 p->childp = Fplist_put (p->childp, option, value);
2641 return Qt;
2642 }
2643
2644 if (NILP (no_error))
2645 error ("Unknown or unsupported option");
2646
2647 return Qnil;
2648 }
2649
2650 \f
2651 DEFUN ("serial-process-configure",
2652 Fserial_process_configure,
2653 Sserial_process_configure,
2654 0, MANY, 0,
2655 doc: /* Configure speed, bytesize, etc. of a serial process.
2656
2657 Arguments are specified as keyword/argument pairs. Attributes that
2658 are not given are re-initialized from the process's current
2659 configuration (available via the function `process-contact') or set to
2660 reasonable default values. The following arguments are defined:
2661
2662 :process PROCESS
2663 :name NAME
2664 :buffer BUFFER
2665 :port PORT
2666 -- Any of these arguments can be given to identify the process that is
2667 to be configured. If none of these arguments is given, the current
2668 buffer's process is used.
2669
2670 :speed SPEED -- SPEED is the speed of the serial port in bits per
2671 second, also called baud rate. Any value can be given for SPEED, but
2672 most serial ports work only at a few defined values between 1200 and
2673 115200, with 9600 being the most common value. If SPEED is nil, the
2674 serial port is not configured any further, i.e., all other arguments
2675 are ignored. This may be useful for special serial ports such as
2676 Bluetooth-to-serial converters which can only be configured through AT
2677 commands. A value of nil for SPEED can be used only when passed
2678 through `make-serial-process' or `serial-term'.
2679
2680 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2681 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2682
2683 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2684 `odd' (use odd parity), or the symbol `even' (use even parity). If
2685 PARITY is not given, no parity is used.
2686
2687 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2688 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2689 is not given or nil, 1 stopbit is used.
2690
2691 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2692 flowcontrol to be used, which is either nil (don't use flowcontrol),
2693 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2694 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2695 flowcontrol is used.
2696
2697 `serial-process-configure' is called by `make-serial-process' for the
2698 initial configuration of the serial port.
2699
2700 Examples:
2701
2702 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2703
2704 \(serial-process-configure
2705 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2706
2707 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2708
2709 usage: (serial-process-configure &rest ARGS) */)
2710 (int nargs, Lisp_Object *args)
2711 {
2712 struct Lisp_Process *p;
2713 Lisp_Object contact = Qnil;
2714 Lisp_Object proc = Qnil;
2715 struct gcpro gcpro1;
2716
2717 contact = Flist (nargs, args);
2718 GCPRO1 (contact);
2719
2720 proc = Fplist_get (contact, QCprocess);
2721 if (NILP (proc))
2722 proc = Fplist_get (contact, QCname);
2723 if (NILP (proc))
2724 proc = Fplist_get (contact, QCbuffer);
2725 if (NILP (proc))
2726 proc = Fplist_get (contact, QCport);
2727 proc = get_process (proc);
2728 p = XPROCESS (proc);
2729 if (!EQ (p->type, Qserial))
2730 error ("Not a serial process");
2731
2732 if (NILP (Fplist_get (p->childp, QCspeed)))
2733 {
2734 UNGCPRO;
2735 return Qnil;
2736 }
2737
2738 serial_configure (p, contact);
2739
2740 UNGCPRO;
2741 return Qnil;
2742 }
2743
2744 /* Used by make-serial-process to recover from errors. */
2745 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2746 {
2747 if (!PROCESSP (proc))
2748 abort ();
2749 remove_process (proc);
2750 return Qnil;
2751 }
2752
2753 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2754 0, MANY, 0,
2755 doc: /* Create and return a serial port process.
2756
2757 In Emacs, serial port connections are represented by process objects,
2758 so input and output work as for subprocesses, and `delete-process'
2759 closes a serial port connection. However, a serial process has no
2760 process id, it cannot be signaled, and the status codes are different
2761 from normal processes.
2762
2763 `make-serial-process' creates a process and a buffer, on which you
2764 probably want to use `process-send-string'. Try \\[serial-term] for
2765 an interactive terminal. See below for examples.
2766
2767 Arguments are specified as keyword/argument pairs. The following
2768 arguments are defined:
2769
2770 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2771 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2772 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2773 the backslashes in strings).
2774
2775 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2776 which is called by `make-serial-process'.
2777
2778 :name NAME -- NAME is the name of the process. If NAME is not given,
2779 the value of PORT is used.
2780
2781 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2782 with the process. Process output goes at the end of that buffer,
2783 unless you specify an output stream or filter function to handle the
2784 output. If BUFFER is not given, the value of NAME is used.
2785
2786 :coding CODING -- If CODING is a symbol, it specifies the coding
2787 system used for both reading and writing for this process. If CODING
2788 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2789 ENCODING is used for writing.
2790
2791 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2792 the process is running. If BOOL is not given, query before exiting.
2793
2794 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2795 In the stopped state, a serial process does not accept incoming data,
2796 but you can send outgoing data. The stopped state is cleared by
2797 `continue-process' and set by `stop-process'.
2798
2799 :filter FILTER -- Install FILTER as the process filter.
2800
2801 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2802
2803 :plist PLIST -- Install PLIST as the initial plist of the process.
2804
2805 :speed
2806 :bytesize
2807 :parity
2808 :stopbits
2809 :flowcontrol
2810 -- These arguments are handled by `serial-process-configure', which is
2811 called by `make-serial-process'.
2812
2813 The original argument list, possibly modified by later configuration,
2814 is available via the function `process-contact'.
2815
2816 Examples:
2817
2818 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2819
2820 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2821
2822 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2823
2824 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2825
2826 usage: (make-serial-process &rest ARGS) */)
2827 (int nargs, Lisp_Object *args)
2828 {
2829 int fd = -1;
2830 Lisp_Object proc, contact, port;
2831 struct Lisp_Process *p;
2832 struct gcpro gcpro1;
2833 Lisp_Object name, buffer;
2834 Lisp_Object tem, val;
2835 int specpdl_count = -1;
2836
2837 if (nargs == 0)
2838 return Qnil;
2839
2840 contact = Flist (nargs, args);
2841 GCPRO1 (contact);
2842
2843 port = Fplist_get (contact, QCport);
2844 if (NILP (port))
2845 error ("No port specified");
2846 CHECK_STRING (port);
2847
2848 if (NILP (Fplist_member (contact, QCspeed)))
2849 error (":speed not specified");
2850 if (!NILP (Fplist_get (contact, QCspeed)))
2851 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2852
2853 name = Fplist_get (contact, QCname);
2854 if (NILP (name))
2855 name = port;
2856 CHECK_STRING (name);
2857 proc = make_process (name);
2858 specpdl_count = SPECPDL_INDEX ();
2859 record_unwind_protect (make_serial_process_unwind, proc);
2860 p = XPROCESS (proc);
2861
2862 fd = serial_open ((char*) SDATA (port));
2863 p->infd = fd;
2864 p->outfd = fd;
2865 if (fd > max_process_desc)
2866 max_process_desc = fd;
2867 chan_process[fd] = proc;
2868
2869 buffer = Fplist_get (contact, QCbuffer);
2870 if (NILP (buffer))
2871 buffer = name;
2872 buffer = Fget_buffer_create (buffer);
2873 p->buffer = buffer;
2874
2875 p->childp = contact;
2876 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2877 p->type = Qserial;
2878 p->sentinel = Fplist_get (contact, QCsentinel);
2879 p->filter = Fplist_get (contact, QCfilter);
2880 p->log = Qnil;
2881 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2882 p->kill_without_query = 1;
2883 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2884 p->command = Qt;
2885 p->pty_flag = 0;
2886
2887 if (!EQ (p->command, Qt))
2888 {
2889 FD_SET (fd, &input_wait_mask);
2890 FD_SET (fd, &non_keyboard_wait_mask);
2891 }
2892
2893 if (BUFFERP (buffer))
2894 {
2895 set_marker_both (p->mark, buffer,
2896 BUF_ZV (XBUFFER (buffer)),
2897 BUF_ZV_BYTE (XBUFFER (buffer)));
2898 }
2899
2900 tem = Fplist_member (contact, QCcoding);
2901 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2902 tem = Qnil;
2903
2904 val = Qnil;
2905 if (!NILP (tem))
2906 {
2907 val = XCAR (XCDR (tem));
2908 if (CONSP (val))
2909 val = XCAR (val);
2910 }
2911 else if (!NILP (Vcoding_system_for_read))
2912 val = Vcoding_system_for_read;
2913 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2914 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2915 val = Qnil;
2916 p->decode_coding_system = val;
2917
2918 val = Qnil;
2919 if (!NILP (tem))
2920 {
2921 val = XCAR (XCDR (tem));
2922 if (CONSP (val))
2923 val = XCDR (val);
2924 }
2925 else if (!NILP (Vcoding_system_for_write))
2926 val = Vcoding_system_for_write;
2927 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2928 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2929 val = Qnil;
2930 p->encode_coding_system = val;
2931
2932 setup_process_coding_systems (proc);
2933 p->decoding_buf = make_uninit_string (0);
2934 p->decoding_carryover = 0;
2935 p->encoding_buf = make_uninit_string (0);
2936 p->inherit_coding_system_flag
2937 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2938
2939 Fserial_process_configure (nargs, args);
2940
2941 specpdl_ptr = specpdl + specpdl_count;
2942
2943 UNGCPRO;
2944 return proc;
2945 }
2946
2947 /* Create a network stream/datagram client/server process. Treated
2948 exactly like a normal process when reading and writing. Primary
2949 differences are in status display and process deletion. A network
2950 connection has no PID; you cannot signal it. All you can do is
2951 stop/continue it and deactivate/close it via delete-process */
2952
2953 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2954 0, MANY, 0,
2955 doc: /* Create and return a network server or client process.
2956
2957 In Emacs, network connections are represented by process objects, so
2958 input and output work as for subprocesses and `delete-process' closes
2959 a network connection. However, a network process has no process id,
2960 it cannot be signaled, and the status codes are different from normal
2961 processes.
2962
2963 Arguments are specified as keyword/argument pairs. The following
2964 arguments are defined:
2965
2966 :name NAME -- NAME is name for process. It is modified if necessary
2967 to make it unique.
2968
2969 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2970 with the process. Process output goes at end of that buffer, unless
2971 you specify an output stream or filter function to handle the output.
2972 BUFFER may be also nil, meaning that this process is not associated
2973 with any buffer.
2974
2975 :host HOST -- HOST is name of the host to connect to, or its IP
2976 address. The symbol `local' specifies the local host. If specified
2977 for a server process, it must be a valid name or address for the local
2978 host, and only clients connecting to that address will be accepted.
2979
2980 :service SERVICE -- SERVICE is name of the service desired, or an
2981 integer specifying a port number to connect to. If SERVICE is t,
2982 a random port number is selected for the server. (If Emacs was
2983 compiled with getaddrinfo, a port number can also be specified as a
2984 string, e.g. "80", as well as an integer. This is not portable.)
2985
2986 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2987 stream type connection, `datagram' creates a datagram type connection,
2988 `seqpacket' creates a reliable datagram connection.
2989
2990 :family FAMILY -- FAMILY is the address (and protocol) family for the
2991 service specified by HOST and SERVICE. The default (nil) is to use
2992 whatever address family (IPv4 or IPv6) that is defined for the host
2993 and port number specified by HOST and SERVICE. Other address families
2994 supported are:
2995 local -- for a local (i.e. UNIX) address specified by SERVICE.
2996 ipv4 -- use IPv4 address family only.
2997 ipv6 -- use IPv6 address family only.
2998
2999 :local ADDRESS -- ADDRESS is the local address used for the connection.
3000 This parameter is ignored when opening a client process. When specified
3001 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3002
3003 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3004 connection. This parameter is ignored when opening a stream server
3005 process. For a datagram server process, it specifies the initial
3006 setting of the remote datagram address. When specified for a client
3007 process, the FAMILY, HOST, and SERVICE args are ignored.
3008
3009 The format of ADDRESS depends on the address family:
3010 - An IPv4 address is represented as an vector of integers [A B C D P]
3011 corresponding to numeric IP address A.B.C.D and port number P.
3012 - A local address is represented as a string with the address in the
3013 local address space.
3014 - An "unsupported family" address is represented by a cons (F . AV)
3015 where F is the family number and AV is a vector containing the socket
3016 address data with one element per address data byte. Do not rely on
3017 this format in portable code, as it may depend on implementation
3018 defined constants, data sizes, and data structure alignment.
3019
3020 :coding CODING -- If CODING is a symbol, it specifies the coding
3021 system used for both reading and writing for this process. If CODING
3022 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3023 ENCODING is used for writing.
3024
3025 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3026 return without waiting for the connection to complete; instead, the
3027 sentinel function will be called with second arg matching "open" (if
3028 successful) or "failed" when the connect completes. Default is to use
3029 a blocking connect (i.e. wait) for stream type connections.
3030
3031 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3032 running when Emacs is exited.
3033
3034 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3035 In the stopped state, a server process does not accept new
3036 connections, and a client process does not handle incoming traffic.
3037 The stopped state is cleared by `continue-process' and set by
3038 `stop-process'.
3039
3040 :filter FILTER -- Install FILTER as the process filter.
3041
3042 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3043 process filter are multibyte, otherwise they are unibyte.
3044 If this keyword is not specified, the strings are multibyte if
3045 `default-enable-multibyte-characters' is non-nil.
3046
3047 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3048
3049 :log LOG -- Install LOG as the server process log function. This
3050 function is called when the server accepts a network connection from a
3051 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3052 is the server process, CLIENT is the new process for the connection,
3053 and MESSAGE is a string.
3054
3055 :plist PLIST -- Install PLIST as the new process' initial plist.
3056
3057 :server QLEN -- if QLEN is non-nil, create a server process for the
3058 specified FAMILY, SERVICE, and connection type (stream or datagram).
3059 If QLEN is an integer, it is used as the max. length of the server's
3060 pending connection queue (also known as the backlog); the default
3061 queue length is 5. Default is to create a client process.
3062
3063 The following network options can be specified for this connection:
3064
3065 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3066 :dontroute BOOL -- Only send to directly connected hosts.
3067 :keepalive BOOL -- Send keep-alive messages on network stream.
3068 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3069 :oobinline BOOL -- Place out-of-band data in receive data stream.
3070 :priority INT -- Set protocol defined priority for sent packets.
3071 :reuseaddr BOOL -- Allow reusing a recently used local address
3072 (this is allowed by default for a server process).
3073 :bindtodevice NAME -- bind to interface NAME. Using this may require
3074 special privileges on some systems.
3075
3076 Consult the relevant system programmer's manual pages for more
3077 information on using these options.
3078
3079
3080 A server process will listen for and accept connections from clients.
3081 When a client connection is accepted, a new network process is created
3082 for the connection with the following parameters:
3083
3084 - The client's process name is constructed by concatenating the server
3085 process' NAME and a client identification string.
3086 - If the FILTER argument is non-nil, the client process will not get a
3087 separate process buffer; otherwise, the client's process buffer is a newly
3088 created buffer named after the server process' BUFFER name or process
3089 NAME concatenated with the client identification string.
3090 - The connection type and the process filter and sentinel parameters are
3091 inherited from the server process' TYPE, FILTER and SENTINEL.
3092 - The client process' contact info is set according to the client's
3093 addressing information (typically an IP address and a port number).
3094 - The client process' plist is initialized from the server's plist.
3095
3096 Notice that the FILTER and SENTINEL args are never used directly by
3097 the server process. Also, the BUFFER argument is not used directly by
3098 the server process, but via the optional :log function, accepted (and
3099 failed) connections may be logged in the server process' buffer.
3100
3101 The original argument list, modified with the actual connection
3102 information, is available via the `process-contact' function.
3103
3104 usage: (make-network-process &rest ARGS) */)
3105 (int nargs, Lisp_Object *args)
3106 {
3107 Lisp_Object proc;
3108 Lisp_Object contact;
3109 struct Lisp_Process *p;
3110 #ifdef HAVE_GETADDRINFO
3111 struct addrinfo ai, *res, *lres;
3112 struct addrinfo hints;
3113 const char *portstring;
3114 char portbuf[128];
3115 #else /* HAVE_GETADDRINFO */
3116 struct _emacs_addrinfo
3117 {
3118 int ai_family;
3119 int ai_socktype;
3120 int ai_protocol;
3121 int ai_addrlen;
3122 struct sockaddr *ai_addr;
3123 struct _emacs_addrinfo *ai_next;
3124 } ai, *res, *lres;
3125 #endif /* HAVE_GETADDRINFO */
3126 struct sockaddr_in address_in;
3127 #ifdef HAVE_LOCAL_SOCKETS
3128 struct sockaddr_un address_un;
3129 #endif
3130 int port;
3131 int ret = 0;
3132 int xerrno = 0;
3133 int s = -1, outch, inch;
3134 struct gcpro gcpro1;
3135 int count = SPECPDL_INDEX ();
3136 int count1;
3137 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3138 Lisp_Object tem;
3139 Lisp_Object name, buffer, host, service, address;
3140 Lisp_Object filter, sentinel;
3141 int is_non_blocking_client = 0;
3142 int is_server = 0, backlog = 5;
3143 int socktype;
3144 int family = -1;
3145
3146 if (nargs == 0)
3147 return Qnil;
3148
3149 /* Save arguments for process-contact and clone-process. */
3150 contact = Flist (nargs, args);
3151 GCPRO1 (contact);
3152
3153 #ifdef WINDOWSNT
3154 /* Ensure socket support is loaded if available. */
3155 init_winsock (TRUE);
3156 #endif
3157
3158 /* :type TYPE (nil: stream, datagram */
3159 tem = Fplist_get (contact, QCtype);
3160 if (NILP (tem))
3161 socktype = SOCK_STREAM;
3162 #ifdef DATAGRAM_SOCKETS
3163 else if (EQ (tem, Qdatagram))
3164 socktype = SOCK_DGRAM;
3165 #endif
3166 #ifdef HAVE_SEQPACKET
3167 else if (EQ (tem, Qseqpacket))
3168 socktype = SOCK_SEQPACKET;
3169 #endif
3170 else
3171 error ("Unsupported connection type");
3172
3173 /* :server BOOL */
3174 tem = Fplist_get (contact, QCserver);
3175 if (!NILP (tem))
3176 {
3177 /* Don't support network sockets when non-blocking mode is
3178 not available, since a blocked Emacs is not useful. */
3179 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3180 error ("Network servers not supported");
3181 #else
3182 is_server = 1;
3183 if (INTEGERP (tem))
3184 backlog = XINT (tem);
3185 #endif
3186 }
3187
3188 /* Make QCaddress an alias for :local (server) or :remote (client). */
3189 QCaddress = is_server ? QClocal : QCremote;
3190
3191 /* :nowait BOOL */
3192 if (!is_server && socktype != SOCK_DGRAM
3193 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3194 {
3195 #ifndef NON_BLOCKING_CONNECT
3196 error ("Non-blocking connect not supported");
3197 #else
3198 is_non_blocking_client = 1;
3199 #endif
3200 }
3201
3202 name = Fplist_get (contact, QCname);
3203 buffer = Fplist_get (contact, QCbuffer);
3204 filter = Fplist_get (contact, QCfilter);
3205 sentinel = Fplist_get (contact, QCsentinel);
3206
3207 CHECK_STRING (name);
3208
3209 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3210 ai.ai_socktype = socktype;
3211 ai.ai_protocol = 0;
3212 ai.ai_next = NULL;
3213 res = &ai;
3214
3215 /* :local ADDRESS or :remote ADDRESS */
3216 address = Fplist_get (contact, QCaddress);
3217 if (!NILP (address))
3218 {
3219 host = service = Qnil;
3220
3221 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3222 error ("Malformed :address");
3223 ai.ai_family = family;
3224 ai.ai_addr = alloca (ai.ai_addrlen);
3225 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3226 goto open_socket;
3227 }
3228
3229 /* :family FAMILY -- nil (for Inet), local, or integer. */
3230 tem = Fplist_get (contact, QCfamily);
3231 if (NILP (tem))
3232 {
3233 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3234 family = AF_UNSPEC;
3235 #else
3236 family = AF_INET;
3237 #endif
3238 }
3239 #ifdef HAVE_LOCAL_SOCKETS
3240 else if (EQ (tem, Qlocal))
3241 family = AF_LOCAL;
3242 #endif
3243 #ifdef AF_INET6
3244 else if (EQ (tem, Qipv6))
3245 family = AF_INET6;
3246 #endif
3247 else if (EQ (tem, Qipv4))
3248 family = AF_INET;
3249 else if (INTEGERP (tem))
3250 family = XINT (tem);
3251 else
3252 error ("Unknown address family");
3253
3254 ai.ai_family = family;
3255
3256 /* :service SERVICE -- string, integer (port number), or t (random port). */
3257 service = Fplist_get (contact, QCservice);
3258
3259 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3260 host = Fplist_get (contact, QChost);
3261 if (!NILP (host))
3262 {
3263 if (EQ (host, Qlocal))
3264 /* Depending on setup, "localhost" may map to different IPv4 and/or
3265 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3266 host = build_string ("127.0.0.1");
3267 CHECK_STRING (host);
3268 }
3269
3270 #ifdef HAVE_LOCAL_SOCKETS
3271 if (family == AF_LOCAL)
3272 {
3273 if (!NILP (host))
3274 {
3275 message (":family local ignores the :host \"%s\" property",
3276 SDATA (host));
3277 contact = Fplist_put (contact, QChost, Qnil);
3278 host = Qnil;
3279 }
3280 CHECK_STRING (service);
3281 memset (&address_un, 0, sizeof address_un);
3282 address_un.sun_family = AF_LOCAL;
3283 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3284 ai.ai_addr = (struct sockaddr *) &address_un;
3285 ai.ai_addrlen = sizeof address_un;
3286 goto open_socket;
3287 }
3288 #endif
3289
3290 /* Slow down polling to every ten seconds.
3291 Some kernels have a bug which causes retrying connect to fail
3292 after a connect. Polling can interfere with gethostbyname too. */
3293 #ifdef POLL_FOR_INPUT
3294 if (socktype != SOCK_DGRAM)
3295 {
3296 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3297 bind_polling_period (10);
3298 }
3299 #endif
3300
3301 #ifdef HAVE_GETADDRINFO
3302 /* If we have a host, use getaddrinfo to resolve both host and service.
3303 Otherwise, use getservbyname to lookup the service. */
3304 if (!NILP (host))
3305 {
3306
3307 /* SERVICE can either be a string or int.
3308 Convert to a C string for later use by getaddrinfo. */
3309 if (EQ (service, Qt))
3310 portstring = "0";
3311 else if (INTEGERP (service))
3312 {
3313 sprintf (portbuf, "%ld", (long) XINT (service));
3314 portstring = portbuf;
3315 }
3316 else
3317 {
3318 CHECK_STRING (service);
3319 portstring = SDATA (service);
3320 }
3321
3322 immediate_quit = 1;
3323 QUIT;
3324 memset (&hints, 0, sizeof (hints));
3325 hints.ai_flags = 0;
3326 hints.ai_family = family;
3327 hints.ai_socktype = socktype;
3328 hints.ai_protocol = 0;
3329
3330 #ifdef HAVE_RES_INIT
3331 res_init ();
3332 #endif
3333
3334 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3335 if (ret)
3336 #ifdef HAVE_GAI_STRERROR
3337 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3338 #else
3339 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3340 #endif
3341 immediate_quit = 0;
3342
3343 goto open_socket;
3344 }
3345 #endif /* HAVE_GETADDRINFO */
3346
3347 /* We end up here if getaddrinfo is not defined, or in case no hostname
3348 has been specified (e.g. for a local server process). */
3349
3350 if (EQ (service, Qt))
3351 port = 0;
3352 else if (INTEGERP (service))
3353 port = htons ((unsigned short) XINT (service));
3354 else
3355 {
3356 struct servent *svc_info;
3357 CHECK_STRING (service);
3358 svc_info = getservbyname (SDATA (service),
3359 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3360 if (svc_info == 0)
3361 error ("Unknown service: %s", SDATA (service));
3362 port = svc_info->s_port;
3363 }
3364
3365 memset (&address_in, 0, sizeof address_in);
3366 address_in.sin_family = family;
3367 address_in.sin_addr.s_addr = INADDR_ANY;
3368 address_in.sin_port = port;
3369
3370 #ifndef HAVE_GETADDRINFO
3371 if (!NILP (host))
3372 {
3373 struct hostent *host_info_ptr;
3374
3375 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3376 as it may `hang' Emacs for a very long time. */
3377 immediate_quit = 1;
3378 QUIT;
3379
3380 #ifdef HAVE_RES_INIT
3381 res_init ();
3382 #endif
3383
3384 host_info_ptr = gethostbyname (SDATA (host));
3385 immediate_quit = 0;
3386
3387 if (host_info_ptr)
3388 {
3389 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3390 host_info_ptr->h_length);
3391 family = host_info_ptr->h_addrtype;
3392 address_in.sin_family = family;
3393 }
3394 else
3395 /* Attempt to interpret host as numeric inet address */
3396 {
3397 unsigned long numeric_addr;
3398 numeric_addr = inet_addr ((char *) SDATA (host));
3399 if (numeric_addr == -1)
3400 error ("Unknown host \"%s\"", SDATA (host));
3401
3402 memcpy (&address_in.sin_addr, &numeric_addr,
3403 sizeof (address_in.sin_addr));
3404 }
3405
3406 }
3407 #endif /* not HAVE_GETADDRINFO */
3408
3409 ai.ai_family = family;
3410 ai.ai_addr = (struct sockaddr *) &address_in;
3411 ai.ai_addrlen = sizeof address_in;
3412
3413 open_socket:
3414
3415 /* Do this in case we never enter the for-loop below. */
3416 count1 = SPECPDL_INDEX ();
3417 s = -1;
3418
3419 for (lres = res; lres; lres = lres->ai_next)
3420 {
3421 int optn, optbits;
3422
3423 retry_connect:
3424
3425 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3426 if (s < 0)
3427 {
3428 xerrno = errno;
3429 continue;
3430 }
3431
3432 #ifdef DATAGRAM_SOCKETS
3433 if (!is_server && socktype == SOCK_DGRAM)
3434 break;
3435 #endif /* DATAGRAM_SOCKETS */
3436
3437 #ifdef NON_BLOCKING_CONNECT
3438 if (is_non_blocking_client)
3439 {
3440 #ifdef O_NONBLOCK
3441 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3442 #else
3443 ret = fcntl (s, F_SETFL, O_NDELAY);
3444 #endif
3445 if (ret < 0)
3446 {
3447 xerrno = errno;
3448 emacs_close (s);
3449 s = -1;
3450 continue;
3451 }
3452 }
3453 #endif
3454
3455 /* Make us close S if quit. */
3456 record_unwind_protect (close_file_unwind, make_number (s));
3457
3458 /* Parse network options in the arg list.
3459 We simply ignore anything which isn't a known option (including other keywords).
3460 An error is signaled if setting a known option fails. */
3461 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3462 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3463
3464 if (is_server)
3465 {
3466 /* Configure as a server socket. */
3467
3468 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3469 explicit :reuseaddr key to override this. */
3470 #ifdef HAVE_LOCAL_SOCKETS
3471 if (family != AF_LOCAL)
3472 #endif
3473 if (!(optbits & (1 << OPIX_REUSEADDR)))
3474 {
3475 int optval = 1;
3476 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3477 report_file_error ("Cannot set reuse option on server socket", Qnil);
3478 }
3479
3480 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3481 report_file_error ("Cannot bind server socket", Qnil);
3482
3483 #ifdef HAVE_GETSOCKNAME
3484 if (EQ (service, Qt))
3485 {
3486 struct sockaddr_in sa1;
3487 int len1 = sizeof (sa1);
3488 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3489 {
3490 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3491 service = make_number (ntohs (sa1.sin_port));
3492 contact = Fplist_put (contact, QCservice, service);
3493 }
3494 }
3495 #endif
3496
3497 if (socktype != SOCK_DGRAM && listen (s, backlog))
3498 report_file_error ("Cannot listen on server socket", Qnil);
3499
3500 break;
3501 }
3502
3503 immediate_quit = 1;
3504 QUIT;
3505
3506 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3507 xerrno = errno;
3508
3509 if (ret == 0 || xerrno == EISCONN)
3510 {
3511 /* The unwind-protect will be discarded afterwards.
3512 Likewise for immediate_quit. */
3513 break;
3514 }
3515
3516 #ifdef NON_BLOCKING_CONNECT
3517 #ifdef EINPROGRESS
3518 if (is_non_blocking_client && xerrno == EINPROGRESS)
3519 break;
3520 #else
3521 #ifdef EWOULDBLOCK
3522 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3523 break;
3524 #endif
3525 #endif
3526 #endif
3527
3528 #ifndef WINDOWSNT
3529 if (xerrno == EINTR)
3530 {
3531 /* Unlike most other syscalls connect() cannot be called
3532 again. (That would return EALREADY.) The proper way to
3533 wait for completion is select(). */
3534 int sc, len;
3535 SELECT_TYPE fdset;
3536 retry_select:
3537 FD_ZERO (&fdset);
3538 FD_SET (s, &fdset);
3539 QUIT;
3540 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3541 (EMACS_TIME *)0);
3542 if (sc == -1)
3543 {
3544 if (errno == EINTR)
3545 goto retry_select;
3546 else
3547 report_file_error ("select failed", Qnil);
3548 }
3549 eassert (sc > 0);
3550
3551 len = sizeof xerrno;
3552 eassert (FD_ISSET (s, &fdset));
3553 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3554 report_file_error ("getsockopt failed", Qnil);
3555 if (xerrno)
3556 errno = xerrno, report_file_error ("error during connect", Qnil);
3557 else
3558 break;
3559 }
3560 #endif /* !WINDOWSNT */
3561
3562 immediate_quit = 0;
3563
3564 /* Discard the unwind protect closing S. */
3565 specpdl_ptr = specpdl + count1;
3566 emacs_close (s);
3567 s = -1;
3568
3569 #ifdef WINDOWSNT
3570 if (xerrno == EINTR)
3571 goto retry_connect;
3572 #endif
3573 }
3574
3575 if (s >= 0)
3576 {
3577 #ifdef DATAGRAM_SOCKETS
3578 if (socktype == SOCK_DGRAM)
3579 {
3580 if (datagram_address[s].sa)
3581 abort ();
3582 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3583 datagram_address[s].len = lres->ai_addrlen;
3584 if (is_server)
3585 {
3586 Lisp_Object remote;
3587 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3588 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3589 {
3590 int rfamily, rlen;
3591 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3592 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3593 conv_lisp_to_sockaddr (rfamily, remote,
3594 datagram_address[s].sa, rlen);
3595 }
3596 }
3597 else
3598 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3599 }
3600 #endif
3601 contact = Fplist_put (contact, QCaddress,
3602 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3603 #ifdef HAVE_GETSOCKNAME
3604 if (!is_server)
3605 {
3606 struct sockaddr_in sa1;
3607 int len1 = sizeof (sa1);
3608 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3609 contact = Fplist_put (contact, QClocal,
3610 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3611 }
3612 #endif
3613 }
3614
3615 immediate_quit = 0;
3616
3617 #ifdef HAVE_GETADDRINFO
3618 if (res != &ai)
3619 {
3620 BLOCK_INPUT;
3621 freeaddrinfo (res);
3622 UNBLOCK_INPUT;
3623 }
3624 #endif
3625
3626 /* Discard the unwind protect for closing S, if any. */
3627 specpdl_ptr = specpdl + count1;
3628
3629 /* Unwind bind_polling_period and request_sigio. */
3630 unbind_to (count, Qnil);
3631
3632 if (s < 0)
3633 {
3634 /* If non-blocking got this far - and failed - assume non-blocking is
3635 not supported after all. This is probably a wrong assumption, but
3636 the normal blocking calls to open-network-stream handles this error
3637 better. */
3638 if (is_non_blocking_client)
3639 return Qnil;
3640
3641 errno = xerrno;
3642 if (is_server)
3643 report_file_error ("make server process failed", contact);
3644 else
3645 report_file_error ("make client process failed", contact);
3646 }
3647
3648 inch = s;
3649 outch = s;
3650
3651 if (!NILP (buffer))
3652 buffer = Fget_buffer_create (buffer);
3653 proc = make_process (name);
3654
3655 chan_process[inch] = proc;
3656
3657 #ifdef O_NONBLOCK
3658 fcntl (inch, F_SETFL, O_NONBLOCK);
3659 #else
3660 #ifdef O_NDELAY
3661 fcntl (inch, F_SETFL, O_NDELAY);
3662 #endif
3663 #endif
3664
3665 p = XPROCESS (proc);
3666
3667 p->childp = contact;
3668 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3669 p->type = Qnetwork;
3670
3671 p->buffer = buffer;
3672 p->sentinel = sentinel;
3673 p->filter = filter;
3674 p->log = Fplist_get (contact, QClog);
3675 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3676 p->kill_without_query = 1;
3677 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3678 p->command = Qt;
3679 p->pid = 0;
3680 p->infd = inch;
3681 p->outfd = outch;
3682 if (is_server && socktype != SOCK_DGRAM)
3683 p->status = Qlisten;
3684
3685 /* Make the process marker point into the process buffer (if any). */
3686 if (BUFFERP (buffer))
3687 set_marker_both (p->mark, buffer,
3688 BUF_ZV (XBUFFER (buffer)),
3689 BUF_ZV_BYTE (XBUFFER (buffer)));
3690
3691 #ifdef NON_BLOCKING_CONNECT
3692 if (is_non_blocking_client)
3693 {
3694 /* We may get here if connect did succeed immediately. However,
3695 in that case, we still need to signal this like a non-blocking
3696 connection. */
3697 p->status = Qconnect;
3698 if (!FD_ISSET (inch, &connect_wait_mask))
3699 {
3700 FD_SET (inch, &connect_wait_mask);
3701 FD_SET (inch, &write_mask);
3702 num_pending_connects++;
3703 }
3704 }
3705 else
3706 #endif
3707 /* A server may have a client filter setting of Qt, but it must
3708 still listen for incoming connects unless it is stopped. */
3709 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3710 || (EQ (p->status, Qlisten) && NILP (p->command)))
3711 {
3712 FD_SET (inch, &input_wait_mask);
3713 FD_SET (inch, &non_keyboard_wait_mask);
3714 }
3715
3716 if (inch > max_process_desc)
3717 max_process_desc = inch;
3718
3719 tem = Fplist_member (contact, QCcoding);
3720 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3721 tem = Qnil; /* No error message (too late!). */
3722
3723 {
3724 /* Setup coding systems for communicating with the network stream. */
3725 struct gcpro gcpro1;
3726 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3727 Lisp_Object coding_systems = Qt;
3728 Lisp_Object args[5], val;
3729
3730 if (!NILP (tem))
3731 {
3732 val = XCAR (XCDR (tem));
3733 if (CONSP (val))
3734 val = XCAR (val);
3735 }
3736 else if (!NILP (Vcoding_system_for_read))
3737 val = Vcoding_system_for_read;
3738 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3739 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3740 /* We dare not decode end-of-line format by setting VAL to
3741 Qraw_text, because the existing Emacs Lisp libraries
3742 assume that they receive bare code including a sequene of
3743 CR LF. */
3744 val = Qnil;
3745 else
3746 {
3747 if (NILP (host) || NILP (service))
3748 coding_systems = Qnil;
3749 else
3750 {
3751 args[0] = Qopen_network_stream, args[1] = name,
3752 args[2] = buffer, args[3] = host, args[4] = service;
3753 GCPRO1 (proc);
3754 coding_systems = Ffind_operation_coding_system (5, args);
3755 UNGCPRO;
3756 }
3757 if (CONSP (coding_systems))
3758 val = XCAR (coding_systems);
3759 else if (CONSP (Vdefault_process_coding_system))
3760 val = XCAR (Vdefault_process_coding_system);
3761 else
3762 val = Qnil;
3763 }
3764 p->decode_coding_system = val;
3765
3766 if (!NILP (tem))
3767 {
3768 val = XCAR (XCDR (tem));
3769 if (CONSP (val))
3770 val = XCDR (val);
3771 }
3772 else if (!NILP (Vcoding_system_for_write))
3773 val = Vcoding_system_for_write;
3774 else if (NILP (current_buffer->enable_multibyte_characters))
3775 val = Qnil;
3776 else
3777 {
3778 if (EQ (coding_systems, Qt))
3779 {
3780 if (NILP (host) || NILP (service))
3781 coding_systems = Qnil;
3782 else
3783 {
3784 args[0] = Qopen_network_stream, args[1] = name,
3785 args[2] = buffer, args[3] = host, args[4] = service;
3786 GCPRO1 (proc);
3787 coding_systems = Ffind_operation_coding_system (5, args);
3788 UNGCPRO;
3789 }
3790 }
3791 if (CONSP (coding_systems))
3792 val = XCDR (coding_systems);
3793 else if (CONSP (Vdefault_process_coding_system))
3794 val = XCDR (Vdefault_process_coding_system);
3795 else
3796 val = Qnil;
3797 }
3798 p->encode_coding_system = val;
3799 }
3800 setup_process_coding_systems (proc);
3801
3802 p->decoding_buf = make_uninit_string (0);
3803 p->decoding_carryover = 0;
3804 p->encoding_buf = make_uninit_string (0);
3805
3806 p->inherit_coding_system_flag
3807 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3808
3809 UNGCPRO;
3810 return proc;
3811 }
3812
3813 \f
3814 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3815
3816 #ifdef SIOCGIFCONF
3817 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3818 doc: /* Return an alist of all network interfaces and their network address.
3819 Each element is a cons, the car of which is a string containing the
3820 interface name, and the cdr is the network address in internal
3821 format; see the description of ADDRESS in `make-network-process'. */)
3822 (void)
3823 {
3824 struct ifconf ifconf;
3825 struct ifreq *ifreqs = NULL;
3826 int ifaces = 0;
3827 int buf_size, s;
3828 Lisp_Object res;
3829
3830 s = socket (AF_INET, SOCK_STREAM, 0);
3831 if (s < 0)
3832 return Qnil;
3833
3834 again:
3835 ifaces += 25;
3836 buf_size = ifaces * sizeof (ifreqs[0]);
3837 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3838 if (!ifreqs)
3839 {
3840 close (s);
3841 return Qnil;
3842 }
3843
3844 ifconf.ifc_len = buf_size;
3845 ifconf.ifc_req = ifreqs;
3846 if (ioctl (s, SIOCGIFCONF, &ifconf))
3847 {
3848 close (s);
3849 return Qnil;
3850 }
3851
3852 if (ifconf.ifc_len == buf_size)
3853 goto again;
3854
3855 close (s);
3856 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3857
3858 res = Qnil;
3859 while (--ifaces >= 0)
3860 {
3861 struct ifreq *ifq = &ifreqs[ifaces];
3862 char namebuf[sizeof (ifq->ifr_name) + 1];
3863 if (ifq->ifr_addr.sa_family != AF_INET)
3864 continue;
3865 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3866 namebuf[sizeof (ifq->ifr_name)] = 0;
3867 res = Fcons (Fcons (build_string (namebuf),
3868 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3869 sizeof (struct sockaddr))),
3870 res);
3871 }
3872
3873 return res;
3874 }
3875 #endif /* SIOCGIFCONF */
3876
3877 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3878
3879 struct ifflag_def {
3880 int flag_bit;
3881 const char *flag_sym;
3882 };
3883
3884 static const struct ifflag_def ifflag_table[] = {
3885 #ifdef IFF_UP
3886 { IFF_UP, "up" },
3887 #endif
3888 #ifdef IFF_BROADCAST
3889 { IFF_BROADCAST, "broadcast" },
3890 #endif
3891 #ifdef IFF_DEBUG
3892 { IFF_DEBUG, "debug" },
3893 #endif
3894 #ifdef IFF_LOOPBACK
3895 { IFF_LOOPBACK, "loopback" },
3896 #endif
3897 #ifdef IFF_POINTOPOINT
3898 { IFF_POINTOPOINT, "pointopoint" },
3899 #endif
3900 #ifdef IFF_RUNNING
3901 { IFF_RUNNING, "running" },
3902 #endif
3903 #ifdef IFF_NOARP
3904 { IFF_NOARP, "noarp" },
3905 #endif
3906 #ifdef IFF_PROMISC
3907 { IFF_PROMISC, "promisc" },
3908 #endif
3909 #ifdef IFF_NOTRAILERS
3910 { IFF_NOTRAILERS, "notrailers" },
3911 #endif
3912 #ifdef IFF_ALLMULTI
3913 { IFF_ALLMULTI, "allmulti" },
3914 #endif
3915 #ifdef IFF_MASTER
3916 { IFF_MASTER, "master" },
3917 #endif
3918 #ifdef IFF_SLAVE
3919 { IFF_SLAVE, "slave" },
3920 #endif
3921 #ifdef IFF_MULTICAST
3922 { IFF_MULTICAST, "multicast" },
3923 #endif
3924 #ifdef IFF_PORTSEL
3925 { IFF_PORTSEL, "portsel" },
3926 #endif
3927 #ifdef IFF_AUTOMEDIA
3928 { IFF_AUTOMEDIA, "automedia" },
3929 #endif
3930 #ifdef IFF_DYNAMIC
3931 { IFF_DYNAMIC, "dynamic" },
3932 #endif
3933 #ifdef IFF_OACTIVE
3934 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3935 #endif
3936 #ifdef IFF_SIMPLEX
3937 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3938 #endif
3939 #ifdef IFF_LINK0
3940 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3941 #endif
3942 #ifdef IFF_LINK1
3943 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3944 #endif
3945 #ifdef IFF_LINK2
3946 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3947 #endif
3948 { 0, 0 }
3949 };
3950
3951 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3952 doc: /* Return information about network interface named IFNAME.
3953 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3954 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3955 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3956 FLAGS is the current flags of the interface. */)
3957 (Lisp_Object ifname)
3958 {
3959 struct ifreq rq;
3960 Lisp_Object res = Qnil;
3961 Lisp_Object elt;
3962 int s;
3963 int any = 0;
3964
3965 CHECK_STRING (ifname);
3966
3967 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3968 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3969
3970 s = socket (AF_INET, SOCK_STREAM, 0);
3971 if (s < 0)
3972 return Qnil;
3973
3974 elt = Qnil;
3975 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3976 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3977 {
3978 int flags = rq.ifr_flags;
3979 const struct ifflag_def *fp;
3980 int fnum;
3981
3982 any++;
3983 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3984 {
3985 if (flags & fp->flag_bit)
3986 {
3987 elt = Fcons (intern (fp->flag_sym), elt);
3988 flags -= fp->flag_bit;
3989 }
3990 }
3991 for (fnum = 0; flags && fnum < 32; fnum++)
3992 {
3993 if (flags & (1 << fnum))
3994 {
3995 elt = Fcons (make_number (fnum), elt);
3996 }
3997 }
3998 }
3999 #endif
4000 res = Fcons (elt, res);
4001
4002 elt = Qnil;
4003 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4004 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4005 {
4006 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4007 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4008 int n;
4009
4010 any++;
4011 for (n = 0; n < 6; n++)
4012 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4013 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4014 }
4015 #endif
4016 res = Fcons (elt, res);
4017
4018 elt = Qnil;
4019 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4020 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4021 {
4022 any++;
4023 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4024 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4025 #else
4026 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4027 #endif
4028 }
4029 #endif
4030 res = Fcons (elt, res);
4031
4032 elt = Qnil;
4033 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4034 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4035 {
4036 any++;
4037 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4038 }
4039 #endif
4040 res = Fcons (elt, res);
4041
4042 elt = Qnil;
4043 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4044 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4045 {
4046 any++;
4047 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4048 }
4049 #endif
4050 res = Fcons (elt, res);
4051
4052 close (s);
4053
4054 return any ? res : Qnil;
4055 }
4056 #endif
4057 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
4058
4059 /* Turn off input and output for process PROC. */
4060
4061 void
4062 deactivate_process (Lisp_Object proc)
4063 {
4064 register int inchannel, outchannel;
4065 register struct Lisp_Process *p = XPROCESS (proc);
4066
4067 inchannel = p->infd;
4068 outchannel = p->outfd;
4069
4070 #ifdef ADAPTIVE_READ_BUFFERING
4071 if (p->read_output_delay > 0)
4072 {
4073 if (--process_output_delay_count < 0)
4074 process_output_delay_count = 0;
4075 p->read_output_delay = 0;
4076 p->read_output_skip = 0;
4077 }
4078 #endif
4079
4080 if (inchannel >= 0)
4081 {
4082 /* Beware SIGCHLD hereabouts. */
4083 flush_pending_output (inchannel);
4084 emacs_close (inchannel);
4085 if (outchannel >= 0 && outchannel != inchannel)
4086 emacs_close (outchannel);
4087
4088 p->infd = -1;
4089 p->outfd = -1;
4090 #ifdef DATAGRAM_SOCKETS
4091 if (DATAGRAM_CHAN_P (inchannel))
4092 {
4093 xfree (datagram_address[inchannel].sa);
4094 datagram_address[inchannel].sa = 0;
4095 datagram_address[inchannel].len = 0;
4096 }
4097 #endif
4098 chan_process[inchannel] = Qnil;
4099 FD_CLR (inchannel, &input_wait_mask);
4100 FD_CLR (inchannel, &non_keyboard_wait_mask);
4101 #ifdef NON_BLOCKING_CONNECT
4102 if (FD_ISSET (inchannel, &connect_wait_mask))
4103 {
4104 FD_CLR (inchannel, &connect_wait_mask);
4105 FD_CLR (inchannel, &write_mask);
4106 if (--num_pending_connects < 0)
4107 abort ();
4108 }
4109 #endif
4110 if (inchannel == max_process_desc)
4111 {
4112 int i;
4113 /* We just closed the highest-numbered process input descriptor,
4114 so recompute the highest-numbered one now. */
4115 max_process_desc = 0;
4116 for (i = 0; i < MAXDESC; i++)
4117 if (!NILP (chan_process[i]))
4118 max_process_desc = i;
4119 }
4120 }
4121 }
4122
4123 \f
4124 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4125 0, 4, 0,
4126 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4127 It is read into the process' buffers or given to their filter functions.
4128 Non-nil arg PROCESS means do not return until some output has been received
4129 from PROCESS.
4130
4131 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4132 and milliseconds to wait; return after that much time whether or not
4133 there is any subprocess output. If SECONDS is a floating point number,
4134 it specifies a fractional number of seconds to wait.
4135 The MILLISEC argument is obsolete and should be avoided.
4136
4137 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4138 from PROCESS, suspending reading output from other processes.
4139 If JUST-THIS-ONE is an integer, don't run any timers either.
4140 Return non-nil if we received any output before the timeout expired. */)
4141 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4142 {
4143 int secs, usecs = 0;
4144
4145 if (! NILP (process))
4146 CHECK_PROCESS (process);
4147 else
4148 just_this_one = Qnil;
4149
4150 if (!NILP (millisec))
4151 { /* Obsolete calling convention using integers rather than floats. */
4152 CHECK_NUMBER (millisec);
4153 if (NILP (seconds))
4154 seconds = make_float (XINT (millisec) / 1000.0);
4155 else
4156 {
4157 CHECK_NUMBER (seconds);
4158 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4159 }
4160 }
4161
4162 if (!NILP (seconds))
4163 {
4164 if (INTEGERP (seconds))
4165 secs = XINT (seconds);
4166 else if (FLOATP (seconds))
4167 {
4168 double timeout = XFLOAT_DATA (seconds);
4169 secs = (int) timeout;
4170 usecs = (int) ((timeout - (double) secs) * 1000000);
4171 }
4172 else
4173 wrong_type_argument (Qnumberp, seconds);
4174
4175 if (secs < 0 || (secs == 0 && usecs == 0))
4176 secs = -1, usecs = 0;
4177 }
4178 else
4179 secs = NILP (process) ? -1 : 0;
4180
4181 return
4182 (wait_reading_process_output (secs, usecs, 0, 0,
4183 Qnil,
4184 !NILP (process) ? XPROCESS (process) : NULL,
4185 NILP (just_this_one) ? 0 :
4186 !INTEGERP (just_this_one) ? 1 : -1)
4187 ? Qt : Qnil);
4188 }
4189
4190 /* Accept a connection for server process SERVER on CHANNEL. */
4191
4192 static int connect_counter = 0;
4193
4194 static void
4195 server_accept_connection (Lisp_Object server, int channel)
4196 {
4197 Lisp_Object proc, caller, name, buffer;
4198 Lisp_Object contact, host, service;
4199 struct Lisp_Process *ps= XPROCESS (server);
4200 struct Lisp_Process *p;
4201 int s;
4202 union u_sockaddr {
4203 struct sockaddr sa;
4204 struct sockaddr_in in;
4205 #ifdef AF_INET6
4206 struct sockaddr_in6 in6;
4207 #endif
4208 #ifdef HAVE_LOCAL_SOCKETS
4209 struct sockaddr_un un;
4210 #endif
4211 } saddr;
4212 int len = sizeof saddr;
4213
4214 s = accept (channel, &saddr.sa, &len);
4215
4216 if (s < 0)
4217 {
4218 int code = errno;
4219
4220 if (code == EAGAIN)
4221 return;
4222 #ifdef EWOULDBLOCK
4223 if (code == EWOULDBLOCK)
4224 return;
4225 #endif
4226
4227 if (!NILP (ps->log))
4228 call3 (ps->log, server, Qnil,
4229 concat3 (build_string ("accept failed with code"),
4230 Fnumber_to_string (make_number (code)),
4231 build_string ("\n")));
4232 return;
4233 }
4234
4235 connect_counter++;
4236
4237 /* Setup a new process to handle the connection. */
4238
4239 /* Generate a unique identification of the caller, and build contact
4240 information for this process. */
4241 host = Qt;
4242 service = Qnil;
4243 switch (saddr.sa.sa_family)
4244 {
4245 case AF_INET:
4246 {
4247 Lisp_Object args[5];
4248 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4249 args[0] = build_string ("%d.%d.%d.%d");
4250 args[1] = make_number (*ip++);
4251 args[2] = make_number (*ip++);
4252 args[3] = make_number (*ip++);
4253 args[4] = make_number (*ip++);
4254 host = Fformat (5, args);
4255 service = make_number (ntohs (saddr.in.sin_port));
4256
4257 args[0] = build_string (" <%s:%d>");
4258 args[1] = host;
4259 args[2] = service;
4260 caller = Fformat (3, args);
4261 }
4262 break;
4263
4264 #ifdef AF_INET6
4265 case AF_INET6:
4266 {
4267 Lisp_Object args[9];
4268 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4269 int i;
4270 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4271 for (i = 0; i < 8; i++)
4272 args[i+1] = make_number (ntohs (ip6[i]));
4273 host = Fformat (9, args);
4274 service = make_number (ntohs (saddr.in.sin_port));
4275
4276 args[0] = build_string (" <[%s]:%d>");
4277 args[1] = host;
4278 args[2] = service;
4279 caller = Fformat (3, args);
4280 }
4281 break;
4282 #endif
4283
4284 #ifdef HAVE_LOCAL_SOCKETS
4285 case AF_LOCAL:
4286 #endif
4287 default:
4288 caller = Fnumber_to_string (make_number (connect_counter));
4289 caller = concat3 (build_string (" <"), caller, build_string (">"));
4290 break;
4291 }
4292
4293 /* Create a new buffer name for this process if it doesn't have a
4294 filter. The new buffer name is based on the buffer name or
4295 process name of the server process concatenated with the caller
4296 identification. */
4297
4298 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4299 buffer = Qnil;
4300 else
4301 {
4302 buffer = ps->buffer;
4303 if (!NILP (buffer))
4304 buffer = Fbuffer_name (buffer);
4305 else
4306 buffer = ps->name;
4307 if (!NILP (buffer))
4308 {
4309 buffer = concat2 (buffer, caller);
4310 buffer = Fget_buffer_create (buffer);
4311 }
4312 }
4313
4314 /* Generate a unique name for the new server process. Combine the
4315 server process name with the caller identification. */
4316
4317 name = concat2 (ps->name, caller);
4318 proc = make_process (name);
4319
4320 chan_process[s] = proc;
4321
4322 #ifdef O_NONBLOCK
4323 fcntl (s, F_SETFL, O_NONBLOCK);
4324 #else
4325 #ifdef O_NDELAY
4326 fcntl (s, F_SETFL, O_NDELAY);
4327 #endif
4328 #endif
4329
4330 p = XPROCESS (proc);
4331
4332 /* Build new contact information for this setup. */
4333 contact = Fcopy_sequence (ps->childp);
4334 contact = Fplist_put (contact, QCserver, Qnil);
4335 contact = Fplist_put (contact, QChost, host);
4336 if (!NILP (service))
4337 contact = Fplist_put (contact, QCservice, service);
4338 contact = Fplist_put (contact, QCremote,
4339 conv_sockaddr_to_lisp (&saddr.sa, len));
4340 #ifdef HAVE_GETSOCKNAME
4341 len = sizeof saddr;
4342 if (getsockname (s, &saddr.sa, &len) == 0)
4343 contact = Fplist_put (contact, QClocal,
4344 conv_sockaddr_to_lisp (&saddr.sa, len));
4345 #endif
4346
4347 p->childp = contact;
4348 p->plist = Fcopy_sequence (ps->plist);
4349 p->type = Qnetwork;
4350
4351 p->buffer = buffer;
4352 p->sentinel = ps->sentinel;
4353 p->filter = ps->filter;
4354 p->command = Qnil;
4355 p->pid = 0;
4356 p->infd = s;
4357 p->outfd = s;
4358 p->status = Qrun;
4359
4360 /* Client processes for accepted connections are not stopped initially. */
4361 if (!EQ (p->filter, Qt))
4362 {
4363 FD_SET (s, &input_wait_mask);
4364 FD_SET (s, &non_keyboard_wait_mask);
4365 }
4366
4367 if (s > max_process_desc)
4368 max_process_desc = s;
4369
4370 /* Setup coding system for new process based on server process.
4371 This seems to be the proper thing to do, as the coding system
4372 of the new process should reflect the settings at the time the
4373 server socket was opened; not the current settings. */
4374
4375 p->decode_coding_system = ps->decode_coding_system;
4376 p->encode_coding_system = ps->encode_coding_system;
4377 setup_process_coding_systems (proc);
4378
4379 p->decoding_buf = make_uninit_string (0);
4380 p->decoding_carryover = 0;
4381 p->encoding_buf = make_uninit_string (0);
4382
4383 p->inherit_coding_system_flag
4384 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4385
4386 if (!NILP (ps->log))
4387 call3 (ps->log, server, proc,
4388 concat3 (build_string ("accept from "),
4389 (STRINGP (host) ? host : build_string ("-")),
4390 build_string ("\n")));
4391
4392 if (!NILP (p->sentinel))
4393 exec_sentinel (proc,
4394 concat3 (build_string ("open from "),
4395 (STRINGP (host) ? host : build_string ("-")),
4396 build_string ("\n")));
4397 }
4398
4399 /* This variable is different from waiting_for_input in keyboard.c.
4400 It is used to communicate to a lisp process-filter/sentinel (via the
4401 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4402 for user-input when that process-filter was called.
4403 waiting_for_input cannot be used as that is by definition 0 when
4404 lisp code is being evalled.
4405 This is also used in record_asynch_buffer_change.
4406 For that purpose, this must be 0
4407 when not inside wait_reading_process_output. */
4408 static int waiting_for_user_input_p;
4409
4410 static Lisp_Object
4411 wait_reading_process_output_unwind (Lisp_Object data)
4412 {
4413 waiting_for_user_input_p = XINT (data);
4414 return Qnil;
4415 }
4416
4417 /* This is here so breakpoints can be put on it. */
4418 static void
4419 wait_reading_process_output_1 (void)
4420 {
4421 }
4422
4423 /* Use a wrapper around select to work around a bug in gdb 5.3.
4424 Normally, the wrapper is optimized away by inlining.
4425
4426 If emacs is stopped inside select, the gdb backtrace doesn't
4427 show the function which called select, so it is practically
4428 impossible to step through wait_reading_process_output. */
4429
4430 #ifndef select
4431 static INLINE int
4432 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4433 {
4434 return select (n, rfd, wfd, xfd, tmo);
4435 }
4436 #define select select_wrapper
4437 #endif
4438
4439 /* Read and dispose of subprocess output while waiting for timeout to
4440 elapse and/or keyboard input to be available.
4441
4442 TIME_LIMIT is:
4443 timeout in seconds, or
4444 zero for no limit, or
4445 -1 means gobble data immediately available but don't wait for any.
4446
4447 MICROSECS is:
4448 an additional duration to wait, measured in microseconds.
4449 If this is nonzero and time_limit is 0, then the timeout
4450 consists of MICROSECS only.
4451
4452 READ_KBD is a lisp value:
4453 0 to ignore keyboard input, or
4454 1 to return when input is available, or
4455 -1 meaning caller will actually read the input, so don't throw to
4456 the quit handler, or
4457
4458 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4459 output that arrives.
4460
4461 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4462 (and gobble terminal input into the buffer if any arrives).
4463
4464 If WAIT_PROC is specified, wait until something arrives from that
4465 process. The return value is true if we read some input from
4466 that process.
4467
4468 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4469 (suspending output from other processes). A negative value
4470 means don't run any timers either.
4471
4472 If WAIT_PROC is specified, then the function returns true if we
4473 received input from that process before the timeout elapsed.
4474 Otherwise, return true if we received input from any process. */
4475
4476 int
4477 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4478 int do_display,
4479 Lisp_Object wait_for_cell,
4480 struct Lisp_Process *wait_proc, int just_wait_proc)
4481 {
4482 register int channel, nfds;
4483 SELECT_TYPE Available;
4484 SELECT_TYPE Writeok;
4485 int check_write;
4486 int check_delay, no_avail;
4487 int xerrno;
4488 Lisp_Object proc;
4489 EMACS_TIME timeout, end_time;
4490 int wait_channel = -1;
4491 int got_some_input = 0;
4492 int count = SPECPDL_INDEX ();
4493
4494 FD_ZERO (&Available);
4495 FD_ZERO (&Writeok);
4496
4497 if (time_limit == 0 && microsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4498 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4499 message ("Blocking call to accept-process-output with quit inhibited!!");
4500
4501 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4502 if (wait_proc != NULL)
4503 wait_channel = wait_proc->infd;
4504
4505 record_unwind_protect (wait_reading_process_output_unwind,
4506 make_number (waiting_for_user_input_p));
4507 waiting_for_user_input_p = read_kbd;
4508
4509 /* Since we may need to wait several times,
4510 compute the absolute time to return at. */
4511 if (time_limit || microsecs)
4512 {
4513 EMACS_GET_TIME (end_time);
4514 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4515 EMACS_ADD_TIME (end_time, end_time, timeout);
4516 }
4517
4518 while (1)
4519 {
4520 int timeout_reduced_for_timers = 0;
4521
4522 /* If calling from keyboard input, do not quit
4523 since we want to return C-g as an input character.
4524 Otherwise, do pending quit if requested. */
4525 if (read_kbd >= 0)
4526 QUIT;
4527 #ifdef SYNC_INPUT
4528 else
4529 process_pending_signals ();
4530 #endif
4531
4532 /* Exit now if the cell we're waiting for became non-nil. */
4533 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4534 break;
4535
4536 /* Compute time from now till when time limit is up */
4537 /* Exit if already run out */
4538 if (time_limit == -1)
4539 {
4540 /* -1 specified for timeout means
4541 gobble output available now
4542 but don't wait at all. */
4543
4544 EMACS_SET_SECS_USECS (timeout, 0, 0);
4545 }
4546 else if (time_limit || microsecs)
4547 {
4548 EMACS_GET_TIME (timeout);
4549 EMACS_SUB_TIME (timeout, end_time, timeout);
4550 if (EMACS_TIME_NEG_P (timeout))
4551 break;
4552 }
4553 else
4554 {
4555 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4556 }
4557
4558 /* Normally we run timers here.
4559 But not if wait_for_cell; in those cases,
4560 the wait is supposed to be short,
4561 and those callers cannot handle running arbitrary Lisp code here. */
4562 if (NILP (wait_for_cell)
4563 && just_wait_proc >= 0)
4564 {
4565 EMACS_TIME timer_delay;
4566
4567 do
4568 {
4569 int old_timers_run = timers_run;
4570 struct buffer *old_buffer = current_buffer;
4571 Lisp_Object old_window = selected_window;
4572
4573 timer_delay = timer_check (1);
4574
4575 /* If a timer has run, this might have changed buffers
4576 an alike. Make read_key_sequence aware of that. */
4577 if (timers_run != old_timers_run
4578 && (old_buffer != current_buffer
4579 || !EQ (old_window, selected_window))
4580 && waiting_for_user_input_p == -1)
4581 record_asynch_buffer_change ();
4582
4583 if (timers_run != old_timers_run && do_display)
4584 /* We must retry, since a timer may have requeued itself
4585 and that could alter the time_delay. */
4586 redisplay_preserve_echo_area (9);
4587 else
4588 break;
4589 }
4590 while (!detect_input_pending ());
4591
4592 /* If there is unread keyboard input, also return. */
4593 if (read_kbd != 0
4594 && requeued_events_pending_p ())
4595 break;
4596
4597 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4598 {
4599 EMACS_TIME difference;
4600 EMACS_SUB_TIME (difference, timer_delay, timeout);
4601 if (EMACS_TIME_NEG_P (difference))
4602 {
4603 timeout = timer_delay;
4604 timeout_reduced_for_timers = 1;
4605 }
4606 }
4607 /* If time_limit is -1, we are not going to wait at all. */
4608 else if (time_limit != -1)
4609 {
4610 /* This is so a breakpoint can be put here. */
4611 wait_reading_process_output_1 ();
4612 }
4613 }
4614
4615 /* Cause C-g and alarm signals to take immediate action,
4616 and cause input available signals to zero out timeout.
4617
4618 It is important that we do this before checking for process
4619 activity. If we get a SIGCHLD after the explicit checks for
4620 process activity, timeout is the only way we will know. */
4621 if (read_kbd < 0)
4622 set_waiting_for_input (&timeout);
4623
4624 /* If status of something has changed, and no input is
4625 available, notify the user of the change right away. After
4626 this explicit check, we'll let the SIGCHLD handler zap
4627 timeout to get our attention. */
4628 if (update_tick != process_tick)
4629 {
4630 SELECT_TYPE Atemp;
4631 SELECT_TYPE Ctemp;
4632
4633 if (kbd_on_hold_p ())
4634 FD_ZERO (&Atemp);
4635 else
4636 Atemp = input_wait_mask;
4637 Ctemp = write_mask;
4638
4639 EMACS_SET_SECS_USECS (timeout, 0, 0);
4640 if ((select (max (max_process_desc, max_input_desc) + 1,
4641 &Atemp,
4642 #ifdef NON_BLOCKING_CONNECT
4643 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4644 #else
4645 (SELECT_TYPE *)0,
4646 #endif
4647 (SELECT_TYPE *)0, &timeout)
4648 <= 0))
4649 {
4650 /* It's okay for us to do this and then continue with
4651 the loop, since timeout has already been zeroed out. */
4652 clear_waiting_for_input ();
4653 status_notify (NULL);
4654 if (do_display) redisplay_preserve_echo_area (13);
4655 }
4656 }
4657
4658 /* Don't wait for output from a non-running process. Just
4659 read whatever data has already been received. */
4660 if (wait_proc && wait_proc->raw_status_new)
4661 update_status (wait_proc);
4662 if (wait_proc
4663 && ! EQ (wait_proc->status, Qrun)
4664 && ! EQ (wait_proc->status, Qconnect))
4665 {
4666 int nread, total_nread = 0;
4667
4668 clear_waiting_for_input ();
4669 XSETPROCESS (proc, wait_proc);
4670
4671 /* Read data from the process, until we exhaust it. */
4672 while (wait_proc->infd >= 0)
4673 {
4674 nread = read_process_output (proc, wait_proc->infd);
4675
4676 if (nread == 0)
4677 break;
4678
4679 if (0 < nread)
4680 {
4681 total_nread += nread;
4682 got_some_input = 1;
4683 }
4684 #ifdef EIO
4685 else if (nread == -1 && EIO == errno)
4686 break;
4687 #endif
4688 #ifdef EAGAIN
4689 else if (nread == -1 && EAGAIN == errno)
4690 break;
4691 #endif
4692 #ifdef EWOULDBLOCK
4693 else if (nread == -1 && EWOULDBLOCK == errno)
4694 break;
4695 #endif
4696 }
4697 if (total_nread > 0 && do_display)
4698 redisplay_preserve_echo_area (10);
4699
4700 break;
4701 }
4702
4703 /* Wait till there is something to do */
4704
4705 if (wait_proc && just_wait_proc)
4706 {
4707 if (wait_proc->infd < 0) /* Terminated */
4708 break;
4709 FD_SET (wait_proc->infd, &Available);
4710 check_delay = 0;
4711 check_write = 0;
4712 }
4713 else if (!NILP (wait_for_cell))
4714 {
4715 Available = non_process_wait_mask;
4716 check_delay = 0;
4717 check_write = 0;
4718 }
4719 else
4720 {
4721 if (! read_kbd)
4722 Available = non_keyboard_wait_mask;
4723 else
4724 Available = input_wait_mask;
4725 Writeok = write_mask;
4726 #ifdef SELECT_CANT_DO_WRITE_MASK
4727 check_write = 0;
4728 #else
4729 check_write = 1;
4730 #endif
4731 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4732 }
4733
4734 /* If frame size has changed or the window is newly mapped,
4735 redisplay now, before we start to wait. There is a race
4736 condition here; if a SIGIO arrives between now and the select
4737 and indicates that a frame is trashed, the select may block
4738 displaying a trashed screen. */
4739 if (frame_garbaged && do_display)
4740 {
4741 clear_waiting_for_input ();
4742 redisplay_preserve_echo_area (11);
4743 if (read_kbd < 0)
4744 set_waiting_for_input (&timeout);
4745 }
4746
4747 no_avail = 0;
4748 if (read_kbd && detect_input_pending ())
4749 {
4750 nfds = 0;
4751 no_avail = 1;
4752 }
4753 else
4754 {
4755
4756 #ifdef ADAPTIVE_READ_BUFFERING
4757 /* Set the timeout for adaptive read buffering if any
4758 process has non-zero read_output_skip and non-zero
4759 read_output_delay, and we are not reading output for a
4760 specific wait_channel. It is not executed if
4761 Vprocess_adaptive_read_buffering is nil. */
4762 if (process_output_skip && check_delay > 0)
4763 {
4764 int usecs = EMACS_USECS (timeout);
4765 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4766 usecs = READ_OUTPUT_DELAY_MAX;
4767 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4768 {
4769 proc = chan_process[channel];
4770 if (NILP (proc))
4771 continue;
4772 /* Find minimum non-zero read_output_delay among the
4773 processes with non-zero read_output_skip. */
4774 if (XPROCESS (proc)->read_output_delay > 0)
4775 {
4776 check_delay--;
4777 if (!XPROCESS (proc)->read_output_skip)
4778 continue;
4779 FD_CLR (channel, &Available);
4780 XPROCESS (proc)->read_output_skip = 0;
4781 if (XPROCESS (proc)->read_output_delay < usecs)
4782 usecs = XPROCESS (proc)->read_output_delay;
4783 }
4784 }
4785 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4786 process_output_skip = 0;
4787 }
4788 #endif
4789 #if defined (USE_GTK) || defined (HAVE_GCONF)
4790 nfds = xg_select
4791 #elif defined (HAVE_NS)
4792 nfds = ns_select
4793 #else
4794 nfds = select
4795 #endif
4796 (max (max_process_desc, max_input_desc) + 1,
4797 &Available,
4798 (check_write ? &Writeok : (SELECT_TYPE *)0),
4799 (SELECT_TYPE *)0, &timeout);
4800 }
4801
4802 xerrno = errno;
4803
4804 /* Make C-g and alarm signals set flags again */
4805 clear_waiting_for_input ();
4806
4807 /* If we woke up due to SIGWINCH, actually change size now. */
4808 do_pending_window_change (0);
4809
4810 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4811 /* We wanted the full specified time, so return now. */
4812 break;
4813 if (nfds < 0)
4814 {
4815 if (xerrno == EINTR)
4816 no_avail = 1;
4817 else if (xerrno == EBADF)
4818 {
4819 #ifdef AIX
4820 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4821 the child's closure of the pts gives the parent a SIGHUP, and
4822 the ptc file descriptor is automatically closed,
4823 yielding EBADF here or at select() call above.
4824 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4825 in m/ibmrt-aix.h), and here we just ignore the select error.
4826 Cleanup occurs c/o status_notify after SIGCLD. */
4827 no_avail = 1; /* Cannot depend on values returned */
4828 #else
4829 abort ();
4830 #endif
4831 }
4832 else
4833 error ("select error: %s", emacs_strerror (xerrno));
4834 }
4835
4836 if (no_avail)
4837 {
4838 FD_ZERO (&Available);
4839 check_write = 0;
4840 }
4841
4842 #if 0 /* When polling is used, interrupt_input is 0,
4843 so get_input_pending should read the input.
4844 So this should not be needed. */
4845 /* If we are using polling for input,
4846 and we see input available, make it get read now.
4847 Otherwise it might not actually get read for a second.
4848 And on hpux, since we turn off polling in wait_reading_process_output,
4849 it might never get read at all if we don't spend much time
4850 outside of wait_reading_process_output. */
4851 if (read_kbd && interrupt_input
4852 && keyboard_bit_set (&Available)
4853 && input_polling_used ())
4854 kill (getpid (), SIGALRM);
4855 #endif
4856
4857 /* Check for keyboard input */
4858 /* If there is any, return immediately
4859 to give it higher priority than subprocesses */
4860
4861 if (read_kbd != 0)
4862 {
4863 int old_timers_run = timers_run;
4864 struct buffer *old_buffer = current_buffer;
4865 Lisp_Object old_window = selected_window;
4866 int leave = 0;
4867
4868 if (detect_input_pending_run_timers (do_display))
4869 {
4870 swallow_events (do_display);
4871 if (detect_input_pending_run_timers (do_display))
4872 leave = 1;
4873 }
4874
4875 /* If a timer has run, this might have changed buffers
4876 an alike. Make read_key_sequence aware of that. */
4877 if (timers_run != old_timers_run
4878 && waiting_for_user_input_p == -1
4879 && (old_buffer != current_buffer
4880 || !EQ (old_window, selected_window)))
4881 record_asynch_buffer_change ();
4882
4883 if (leave)
4884 break;
4885 }
4886
4887 /* If there is unread keyboard input, also return. */
4888 if (read_kbd != 0
4889 && requeued_events_pending_p ())
4890 break;
4891
4892 /* If we are not checking for keyboard input now,
4893 do process events (but don't run any timers).
4894 This is so that X events will be processed.
4895 Otherwise they may have to wait until polling takes place.
4896 That would causes delays in pasting selections, for example.
4897
4898 (We used to do this only if wait_for_cell.) */
4899 if (read_kbd == 0 && detect_input_pending ())
4900 {
4901 swallow_events (do_display);
4902 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4903 if (detect_input_pending ())
4904 break;
4905 #endif
4906 }
4907
4908 /* Exit now if the cell we're waiting for became non-nil. */
4909 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4910 break;
4911
4912 #ifdef SIGIO
4913 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4914 go read it. This can happen with X on BSD after logging out.
4915 In that case, there really is no input and no SIGIO,
4916 but select says there is input. */
4917
4918 if (read_kbd && interrupt_input
4919 && keyboard_bit_set (&Available) && ! noninteractive)
4920 kill (getpid (), SIGIO);
4921 #endif
4922
4923 if (! wait_proc)
4924 got_some_input |= nfds > 0;
4925
4926 /* If checking input just got us a size-change event from X,
4927 obey it now if we should. */
4928 if (read_kbd || ! NILP (wait_for_cell))
4929 do_pending_window_change (0);
4930
4931 /* Check for data from a process. */
4932 if (no_avail || nfds == 0)
4933 continue;
4934
4935 for (channel = 0; channel <= max_input_desc; ++channel)
4936 {
4937 struct fd_callback_data *d = &fd_callback_info[channel];
4938 if (FD_ISSET (channel, &Available)
4939 && d->func != 0
4940 && (d->condition & FOR_READ) != 0)
4941 d->func (channel, d->data, 1);
4942 if (FD_ISSET (channel, &write_mask)
4943 && d->func != 0
4944 && (d->condition & FOR_WRITE) != 0)
4945 d->func (channel, d->data, 0);
4946 }
4947
4948 /* Really FIRST_PROC_DESC should be 0 on Unix,
4949 but this is safer in the short run. */
4950 for (channel = 0; channel <= max_process_desc; channel++)
4951 {
4952 if (FD_ISSET (channel, &Available)
4953 && FD_ISSET (channel, &non_keyboard_wait_mask)
4954 && !FD_ISSET (channel, &non_process_wait_mask))
4955 {
4956 int nread;
4957
4958 /* If waiting for this channel, arrange to return as
4959 soon as no more input to be processed. No more
4960 waiting. */
4961 if (wait_channel == channel)
4962 {
4963 wait_channel = -1;
4964 time_limit = -1;
4965 got_some_input = 1;
4966 }
4967 proc = chan_process[channel];
4968 if (NILP (proc))
4969 continue;
4970
4971 /* If this is a server stream socket, accept connection. */
4972 if (EQ (XPROCESS (proc)->status, Qlisten))
4973 {
4974 server_accept_connection (proc, channel);
4975 continue;
4976 }
4977
4978 /* Read data from the process, starting with our
4979 buffered-ahead character if we have one. */
4980
4981 nread = read_process_output (proc, channel);
4982 if (nread > 0)
4983 {
4984 /* Since read_process_output can run a filter,
4985 which can call accept-process-output,
4986 don't try to read from any other processes
4987 before doing the select again. */
4988 FD_ZERO (&Available);
4989
4990 if (do_display)
4991 redisplay_preserve_echo_area (12);
4992 }
4993 #ifdef EWOULDBLOCK
4994 else if (nread == -1 && errno == EWOULDBLOCK)
4995 ;
4996 #endif
4997 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4998 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4999 #ifdef O_NONBLOCK
5000 else if (nread == -1 && errno == EAGAIN)
5001 ;
5002 #else
5003 #ifdef O_NDELAY
5004 else if (nread == -1 && errno == EAGAIN)
5005 ;
5006 /* Note that we cannot distinguish between no input
5007 available now and a closed pipe.
5008 With luck, a closed pipe will be accompanied by
5009 subprocess termination and SIGCHLD. */
5010 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5011 ;
5012 #endif /* O_NDELAY */
5013 #endif /* O_NONBLOCK */
5014 #ifdef HAVE_PTYS
5015 /* On some OSs with ptys, when the process on one end of
5016 a pty exits, the other end gets an error reading with
5017 errno = EIO instead of getting an EOF (0 bytes read).
5018 Therefore, if we get an error reading and errno =
5019 EIO, just continue, because the child process has
5020 exited and should clean itself up soon (e.g. when we
5021 get a SIGCHLD).
5022
5023 However, it has been known to happen that the SIGCHLD
5024 got lost. So raise the signal again just in case.
5025 It can't hurt. */
5026 else if (nread == -1 && errno == EIO)
5027 {
5028 /* Clear the descriptor now, so we only raise the
5029 signal once. Don't do this if `process' is only
5030 a pty. */
5031 if (XPROCESS (proc)->pid != -2)
5032 {
5033 FD_CLR (channel, &input_wait_mask);
5034 FD_CLR (channel, &non_keyboard_wait_mask);
5035
5036 kill (getpid (), SIGCHLD);
5037 }
5038 }
5039 #endif /* HAVE_PTYS */
5040 /* If we can detect process termination, don't consider the process
5041 gone just because its pipe is closed. */
5042 #ifdef SIGCHLD
5043 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5044 ;
5045 #endif
5046 else
5047 {
5048 /* Preserve status of processes already terminated. */
5049 XPROCESS (proc)->tick = ++process_tick;
5050 deactivate_process (proc);
5051 if (XPROCESS (proc)->raw_status_new)
5052 update_status (XPROCESS (proc));
5053 if (EQ (XPROCESS (proc)->status, Qrun))
5054 XPROCESS (proc)->status
5055 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5056 }
5057 }
5058 #ifdef NON_BLOCKING_CONNECT
5059 if (FD_ISSET (channel, &Writeok)
5060 && FD_ISSET (channel, &connect_wait_mask))
5061 {
5062 struct Lisp_Process *p;
5063
5064 FD_CLR (channel, &connect_wait_mask);
5065 FD_CLR (channel, &write_mask);
5066 if (--num_pending_connects < 0)
5067 abort ();
5068
5069 proc = chan_process[channel];
5070 if (NILP (proc))
5071 continue;
5072
5073 p = XPROCESS (proc);
5074
5075 #ifdef GNU_LINUX
5076 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5077 So only use it on systems where it is known to work. */
5078 {
5079 int xlen = sizeof (xerrno);
5080 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5081 xerrno = errno;
5082 }
5083 #else
5084 {
5085 struct sockaddr pname;
5086 int pnamelen = sizeof (pname);
5087
5088 /* If connection failed, getpeername will fail. */
5089 xerrno = 0;
5090 if (getpeername (channel, &pname, &pnamelen) < 0)
5091 {
5092 /* Obtain connect failure code through error slippage. */
5093 char dummy;
5094 xerrno = errno;
5095 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5096 xerrno = errno;
5097 }
5098 }
5099 #endif
5100 if (xerrno)
5101 {
5102 p->tick = ++process_tick;
5103 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5104 deactivate_process (proc);
5105 }
5106 else
5107 {
5108 p->status = Qrun;
5109 /* Execute the sentinel here. If we had relied on
5110 status_notify to do it later, it will read input
5111 from the process before calling the sentinel. */
5112 exec_sentinel (proc, build_string ("open\n"));
5113 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5114 {
5115 FD_SET (p->infd, &input_wait_mask);
5116 FD_SET (p->infd, &non_keyboard_wait_mask);
5117 }
5118 }
5119 }
5120 #endif /* NON_BLOCKING_CONNECT */
5121 } /* end for each file descriptor */
5122 } /* end while exit conditions not met */
5123
5124 unbind_to (count, Qnil);
5125
5126 /* If calling from keyboard input, do not quit
5127 since we want to return C-g as an input character.
5128 Otherwise, do pending quit if requested. */
5129 if (read_kbd >= 0)
5130 {
5131 /* Prevent input_pending from remaining set if we quit. */
5132 clear_input_pending ();
5133 QUIT;
5134 }
5135
5136 return got_some_input;
5137 }
5138 \f
5139 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5140
5141 static Lisp_Object
5142 read_process_output_call (Lisp_Object fun_and_args)
5143 {
5144 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5145 }
5146
5147 static Lisp_Object
5148 read_process_output_error_handler (Lisp_Object error)
5149 {
5150 cmd_error_internal (error, "error in process filter: ");
5151 Vinhibit_quit = Qt;
5152 update_echo_area ();
5153 Fsleep_for (make_number (2), Qnil);
5154 return Qt;
5155 }
5156
5157 /* Read pending output from the process channel,
5158 starting with our buffered-ahead character if we have one.
5159 Yield number of decoded characters read.
5160
5161 This function reads at most 4096 characters.
5162 If you want to read all available subprocess output,
5163 you must call it repeatedly until it returns zero.
5164
5165 The characters read are decoded according to PROC's coding-system
5166 for decoding. */
5167
5168 static int
5169 read_process_output (Lisp_Object proc, register int channel)
5170 {
5171 register int nbytes;
5172 char *chars;
5173 register Lisp_Object outstream;
5174 register struct Lisp_Process *p = XPROCESS (proc);
5175 register EMACS_INT opoint;
5176 struct coding_system *coding = proc_decode_coding_system[channel];
5177 int carryover = p->decoding_carryover;
5178 int readmax = 4096;
5179 int count = SPECPDL_INDEX ();
5180 Lisp_Object odeactivate;
5181
5182 chars = (char *) alloca (carryover + readmax);
5183 if (carryover)
5184 /* See the comment above. */
5185 memcpy (chars, SDATA (p->decoding_buf), carryover);
5186
5187 #ifdef DATAGRAM_SOCKETS
5188 /* We have a working select, so proc_buffered_char is always -1. */
5189 if (DATAGRAM_CHAN_P (channel))
5190 {
5191 int len = datagram_address[channel].len;
5192 nbytes = recvfrom (channel, chars + carryover, readmax,
5193 0, datagram_address[channel].sa, &len);
5194 }
5195 else
5196 #endif
5197 if (proc_buffered_char[channel] < 0)
5198 {
5199 #ifdef HAVE_GNUTLS
5200 if (XPROCESS (proc)->gnutls_p)
5201 nbytes = emacs_gnutls_read (channel, XPROCESS (proc),
5202 chars + carryover, readmax);
5203 else
5204 #endif
5205 nbytes = emacs_read (channel, chars + carryover, readmax);
5206 #ifdef ADAPTIVE_READ_BUFFERING
5207 if (nbytes > 0 && p->adaptive_read_buffering)
5208 {
5209 int delay = p->read_output_delay;
5210 if (nbytes < 256)
5211 {
5212 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5213 {
5214 if (delay == 0)
5215 process_output_delay_count++;
5216 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5217 }
5218 }
5219 else if (delay > 0 && (nbytes == readmax))
5220 {
5221 delay -= READ_OUTPUT_DELAY_INCREMENT;
5222 if (delay == 0)
5223 process_output_delay_count--;
5224 }
5225 p->read_output_delay = delay;
5226 if (delay)
5227 {
5228 p->read_output_skip = 1;
5229 process_output_skip = 1;
5230 }
5231 }
5232 #endif
5233 }
5234 else
5235 {
5236 chars[carryover] = proc_buffered_char[channel];
5237 proc_buffered_char[channel] = -1;
5238 #ifdef HAVE_GNUTLS
5239 if (XPROCESS (proc)->gnutls_p)
5240 nbytes = emacs_gnutls_read (channel, XPROCESS (proc),
5241 chars + carryover + 1, readmax - 1);
5242 else
5243 #endif
5244 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5245 if (nbytes < 0)
5246 nbytes = 1;
5247 else
5248 nbytes = nbytes + 1;
5249 }
5250
5251 p->decoding_carryover = 0;
5252
5253 /* At this point, NBYTES holds number of bytes just received
5254 (including the one in proc_buffered_char[channel]). */
5255 if (nbytes <= 0)
5256 {
5257 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5258 return nbytes;
5259 coding->mode |= CODING_MODE_LAST_BLOCK;
5260 }
5261
5262 /* Now set NBYTES how many bytes we must decode. */
5263 nbytes += carryover;
5264
5265 odeactivate = Vdeactivate_mark;
5266 /* There's no good reason to let process filters change the current
5267 buffer, and many callers of accept-process-output, sit-for, and
5268 friends don't expect current-buffer to be changed from under them. */
5269 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5270
5271 /* Read and dispose of the process output. */
5272 outstream = p->filter;
5273 if (!NILP (outstream))
5274 {
5275 Lisp_Object obuffer, okeymap;
5276 Lisp_Object text;
5277 int outer_running_asynch_code = running_asynch_code;
5278 int waiting = waiting_for_user_input_p;
5279
5280 /* No need to gcpro these, because all we do with them later
5281 is test them for EQness, and none of them should be a string. */
5282 XSETBUFFER (obuffer, current_buffer);
5283 okeymap = current_buffer->keymap;
5284
5285 /* We inhibit quit here instead of just catching it so that
5286 hitting ^G when a filter happens to be running won't screw
5287 it up. */
5288 specbind (Qinhibit_quit, Qt);
5289 specbind (Qlast_nonmenu_event, Qt);
5290
5291 /* In case we get recursively called,
5292 and we already saved the match data nonrecursively,
5293 save the same match data in safely recursive fashion. */
5294 if (outer_running_asynch_code)
5295 {
5296 Lisp_Object tem;
5297 /* Don't clobber the CURRENT match data, either! */
5298 tem = Fmatch_data (Qnil, Qnil, Qnil);
5299 restore_search_regs ();
5300 record_unwind_save_match_data ();
5301 Fset_match_data (tem, Qt);
5302 }
5303
5304 /* For speed, if a search happens within this code,
5305 save the match data in a special nonrecursive fashion. */
5306 running_asynch_code = 1;
5307
5308 decode_coding_c_string (coding, chars, nbytes, Qt);
5309 text = coding->dst_object;
5310 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5311 /* A new coding system might be found. */
5312 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5313 {
5314 p->decode_coding_system = Vlast_coding_system_used;
5315
5316 /* Don't call setup_coding_system for
5317 proc_decode_coding_system[channel] here. It is done in
5318 detect_coding called via decode_coding above. */
5319
5320 /* If a coding system for encoding is not yet decided, we set
5321 it as the same as coding-system for decoding.
5322
5323 But, before doing that we must check if
5324 proc_encode_coding_system[p->outfd] surely points to a
5325 valid memory because p->outfd will be changed once EOF is
5326 sent to the process. */
5327 if (NILP (p->encode_coding_system)
5328 && proc_encode_coding_system[p->outfd])
5329 {
5330 p->encode_coding_system
5331 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5332 setup_coding_system (p->encode_coding_system,
5333 proc_encode_coding_system[p->outfd]);
5334 }
5335 }
5336
5337 if (coding->carryover_bytes > 0)
5338 {
5339 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5340 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5341 memcpy (SDATA (p->decoding_buf), coding->carryover,
5342 coding->carryover_bytes);
5343 p->decoding_carryover = coding->carryover_bytes;
5344 }
5345 if (SBYTES (text) > 0)
5346 internal_condition_case_1 (read_process_output_call,
5347 Fcons (outstream,
5348 Fcons (proc, Fcons (text, Qnil))),
5349 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5350 read_process_output_error_handler);
5351
5352 /* If we saved the match data nonrecursively, restore it now. */
5353 restore_search_regs ();
5354 running_asynch_code = outer_running_asynch_code;
5355
5356 /* Restore waiting_for_user_input_p as it was
5357 when we were called, in case the filter clobbered it. */
5358 waiting_for_user_input_p = waiting;
5359
5360 #if 0 /* Call record_asynch_buffer_change unconditionally,
5361 because we might have changed minor modes or other things
5362 that affect key bindings. */
5363 if (! EQ (Fcurrent_buffer (), obuffer)
5364 || ! EQ (current_buffer->keymap, okeymap))
5365 #endif
5366 /* But do it only if the caller is actually going to read events.
5367 Otherwise there's no need to make him wake up, and it could
5368 cause trouble (for example it would make sit_for return). */
5369 if (waiting_for_user_input_p == -1)
5370 record_asynch_buffer_change ();
5371 }
5372
5373 /* If no filter, write into buffer if it isn't dead. */
5374 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5375 {
5376 Lisp_Object old_read_only;
5377 EMACS_INT old_begv, old_zv;
5378 EMACS_INT old_begv_byte, old_zv_byte;
5379 EMACS_INT before, before_byte;
5380 EMACS_INT opoint_byte;
5381 Lisp_Object text;
5382 struct buffer *b;
5383
5384 Fset_buffer (p->buffer);
5385 opoint = PT;
5386 opoint_byte = PT_BYTE;
5387 old_read_only = current_buffer->read_only;
5388 old_begv = BEGV;
5389 old_zv = ZV;
5390 old_begv_byte = BEGV_BYTE;
5391 old_zv_byte = ZV_BYTE;
5392
5393 current_buffer->read_only = Qnil;
5394
5395 /* Insert new output into buffer
5396 at the current end-of-output marker,
5397 thus preserving logical ordering of input and output. */
5398 if (XMARKER (p->mark)->buffer)
5399 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5400 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5401 ZV_BYTE));
5402 else
5403 SET_PT_BOTH (ZV, ZV_BYTE);
5404 before = PT;
5405 before_byte = PT_BYTE;
5406
5407 /* If the output marker is outside of the visible region, save
5408 the restriction and widen. */
5409 if (! (BEGV <= PT && PT <= ZV))
5410 Fwiden ();
5411
5412 decode_coding_c_string (coding, chars, nbytes, Qt);
5413 text = coding->dst_object;
5414 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5415 /* A new coding system might be found. See the comment in the
5416 similar code in the previous `if' block. */
5417 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5418 {
5419 p->decode_coding_system = Vlast_coding_system_used;
5420 if (NILP (p->encode_coding_system)
5421 && proc_encode_coding_system[p->outfd])
5422 {
5423 p->encode_coding_system
5424 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5425 setup_coding_system (p->encode_coding_system,
5426 proc_encode_coding_system[p->outfd]);
5427 }
5428 }
5429 if (coding->carryover_bytes > 0)
5430 {
5431 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5432 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5433 memcpy (SDATA (p->decoding_buf), coding->carryover,
5434 coding->carryover_bytes);
5435 p->decoding_carryover = coding->carryover_bytes;
5436 }
5437 /* Adjust the multibyteness of TEXT to that of the buffer. */
5438 if (NILP (current_buffer->enable_multibyte_characters)
5439 != ! STRING_MULTIBYTE (text))
5440 text = (STRING_MULTIBYTE (text)
5441 ? Fstring_as_unibyte (text)
5442 : Fstring_to_multibyte (text));
5443 /* Insert before markers in case we are inserting where
5444 the buffer's mark is, and the user's next command is Meta-y. */
5445 insert_from_string_before_markers (text, 0, 0,
5446 SCHARS (text), SBYTES (text), 0);
5447
5448 /* Make sure the process marker's position is valid when the
5449 process buffer is changed in the signal_after_change above.
5450 W3 is known to do that. */
5451 if (BUFFERP (p->buffer)
5452 && (b = XBUFFER (p->buffer), b != current_buffer))
5453 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5454 else
5455 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5456
5457 update_mode_lines++;
5458
5459 /* Make sure opoint and the old restrictions
5460 float ahead of any new text just as point would. */
5461 if (opoint >= before)
5462 {
5463 opoint += PT - before;
5464 opoint_byte += PT_BYTE - before_byte;
5465 }
5466 if (old_begv > before)
5467 {
5468 old_begv += PT - before;
5469 old_begv_byte += PT_BYTE - before_byte;
5470 }
5471 if (old_zv >= before)
5472 {
5473 old_zv += PT - before;
5474 old_zv_byte += PT_BYTE - before_byte;
5475 }
5476
5477 /* If the restriction isn't what it should be, set it. */
5478 if (old_begv != BEGV || old_zv != ZV)
5479 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5480
5481
5482 current_buffer->read_only = old_read_only;
5483 SET_PT_BOTH (opoint, opoint_byte);
5484 }
5485 /* Handling the process output should not deactivate the mark. */
5486 Vdeactivate_mark = odeactivate;
5487
5488 unbind_to (count, Qnil);
5489 return nbytes;
5490 }
5491 \f
5492 /* Sending data to subprocess */
5493
5494 jmp_buf send_process_frame;
5495 Lisp_Object process_sent_to;
5496
5497 SIGTYPE
5498 send_process_trap (int ignore)
5499 {
5500 SIGNAL_THREAD_CHECK (SIGPIPE);
5501 sigunblock (sigmask (SIGPIPE));
5502 longjmp (send_process_frame, 1);
5503 }
5504
5505 /* Send some data to process PROC.
5506 BUF is the beginning of the data; LEN is the number of characters.
5507 OBJECT is the Lisp object that the data comes from. If OBJECT is
5508 nil or t, it means that the data comes from C string.
5509
5510 If OBJECT is not nil, the data is encoded by PROC's coding-system
5511 for encoding before it is sent.
5512
5513 This function can evaluate Lisp code and can garbage collect. */
5514
5515 static void
5516 send_process (volatile Lisp_Object proc, const unsigned char *volatile buf,
5517 volatile EMACS_INT len, volatile Lisp_Object object)
5518 {
5519 /* Use volatile to protect variables from being clobbered by longjmp. */
5520 struct Lisp_Process *p = XPROCESS (proc);
5521 EMACS_INT rv;
5522 struct coding_system *coding;
5523 struct gcpro gcpro1;
5524 SIGTYPE (*volatile old_sigpipe) (int);
5525
5526 GCPRO1 (object);
5527
5528 if (p->raw_status_new)
5529 update_status (p);
5530 if (! EQ (p->status, Qrun))
5531 error ("Process %s not running", SDATA (p->name));
5532 if (p->outfd < 0)
5533 error ("Output file descriptor of %s is closed", SDATA (p->name));
5534
5535 coding = proc_encode_coding_system[p->outfd];
5536 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5537
5538 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5539 || (BUFFERP (object)
5540 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5541 || EQ (object, Qt))
5542 {
5543 p->encode_coding_system
5544 = complement_process_encoding_system (p->encode_coding_system);
5545 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5546 {
5547 /* The coding system for encoding was changed to raw-text
5548 because we sent a unibyte text previously. Now we are
5549 sending a multibyte text, thus we must encode it by the
5550 original coding system specified for the current process.
5551
5552 Another reason we comming here is that the coding system
5553 was just complemented and new one was returned by
5554 complement_process_encoding_system. */
5555 setup_coding_system (p->encode_coding_system, coding);
5556 Vlast_coding_system_used = p->encode_coding_system;
5557 }
5558 coding->src_multibyte = 1;
5559 }
5560 else
5561 {
5562 /* For sending a unibyte text, character code conversion should
5563 not take place but EOL conversion should. So, setup raw-text
5564 or one of the subsidiary if we have not yet done it. */
5565 if (CODING_REQUIRE_ENCODING (coding))
5566 {
5567 if (CODING_REQUIRE_FLUSHING (coding))
5568 {
5569 /* But, before changing the coding, we must flush out data. */
5570 coding->mode |= CODING_MODE_LAST_BLOCK;
5571 send_process (proc, "", 0, Qt);
5572 coding->mode &= CODING_MODE_LAST_BLOCK;
5573 }
5574 setup_coding_system (raw_text_coding_system
5575 (Vlast_coding_system_used),
5576 coding);
5577 coding->src_multibyte = 0;
5578 }
5579 }
5580 coding->dst_multibyte = 0;
5581
5582 if (CODING_REQUIRE_ENCODING (coding))
5583 {
5584 coding->dst_object = Qt;
5585 if (BUFFERP (object))
5586 {
5587 EMACS_INT from_byte, from, to;
5588 EMACS_INT save_pt, save_pt_byte;
5589 struct buffer *cur = current_buffer;
5590
5591 set_buffer_internal (XBUFFER (object));
5592 save_pt = PT, save_pt_byte = PT_BYTE;
5593
5594 from_byte = PTR_BYTE_POS (buf);
5595 from = BYTE_TO_CHAR (from_byte);
5596 to = BYTE_TO_CHAR (from_byte + len);
5597 TEMP_SET_PT_BOTH (from, from_byte);
5598 encode_coding_object (coding, object, from, from_byte,
5599 to, from_byte + len, Qt);
5600 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5601 set_buffer_internal (cur);
5602 }
5603 else if (STRINGP (object))
5604 {
5605 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5606 SBYTES (object), Qt);
5607 }
5608 else
5609 {
5610 coding->dst_object = make_unibyte_string (buf, len);
5611 coding->produced = len;
5612 }
5613
5614 len = coding->produced;
5615 object = coding->dst_object;
5616 buf = SDATA (object);
5617 }
5618
5619 if (pty_max_bytes == 0)
5620 {
5621 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5622 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5623 if (pty_max_bytes < 0)
5624 pty_max_bytes = 250;
5625 #else
5626 pty_max_bytes = 250;
5627 #endif
5628 /* Deduct one, to leave space for the eof. */
5629 pty_max_bytes--;
5630 }
5631
5632 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5633 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5634 when returning with longjmp despite being declared volatile. */
5635 if (!setjmp (send_process_frame))
5636 {
5637 process_sent_to = proc;
5638 while (len > 0)
5639 {
5640 EMACS_INT this = len;
5641
5642 /* Send this batch, using one or more write calls. */
5643 while (this > 0)
5644 {
5645 int outfd = p->outfd;
5646 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5647 #ifdef DATAGRAM_SOCKETS
5648 if (DATAGRAM_CHAN_P (outfd))
5649 {
5650 rv = sendto (outfd, (char *) buf, this,
5651 0, datagram_address[outfd].sa,
5652 datagram_address[outfd].len);
5653 if (rv < 0 && errno == EMSGSIZE)
5654 {
5655 signal (SIGPIPE, old_sigpipe);
5656 report_file_error ("sending datagram",
5657 Fcons (proc, Qnil));
5658 }
5659 }
5660 else
5661 #endif
5662 {
5663 #ifdef HAVE_GNUTLS
5664 if (XPROCESS (proc)->gnutls_p)
5665 rv = emacs_gnutls_write (outfd,
5666 XPROCESS (proc),
5667 (char *) buf, this);
5668 else
5669 #endif
5670 rv = emacs_write (outfd, (char *) buf, this);
5671 #ifdef ADAPTIVE_READ_BUFFERING
5672 if (p->read_output_delay > 0
5673 && p->adaptive_read_buffering == 1)
5674 {
5675 p->read_output_delay = 0;
5676 process_output_delay_count--;
5677 p->read_output_skip = 0;
5678 }
5679 #endif
5680 }
5681 signal (SIGPIPE, old_sigpipe);
5682
5683 if (rv < 0)
5684 {
5685 if (0
5686 #ifdef EWOULDBLOCK
5687 || errno == EWOULDBLOCK
5688 #endif
5689 #ifdef EAGAIN
5690 || errno == EAGAIN
5691 #endif
5692 )
5693 /* Buffer is full. Wait, accepting input;
5694 that may allow the program
5695 to finish doing output and read more. */
5696 {
5697 int offset = 0;
5698
5699 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5700 /* A gross hack to work around a bug in FreeBSD.
5701 In the following sequence, read(2) returns
5702 bogus data:
5703
5704 write(2) 1022 bytes
5705 write(2) 954 bytes, get EAGAIN
5706 read(2) 1024 bytes in process_read_output
5707 read(2) 11 bytes in process_read_output
5708
5709 That is, read(2) returns more bytes than have
5710 ever been written successfully. The 1033 bytes
5711 read are the 1022 bytes written successfully
5712 after processing (for example with CRs added if
5713 the terminal is set up that way which it is
5714 here). The same bytes will be seen again in a
5715 later read(2), without the CRs. */
5716
5717 if (errno == EAGAIN)
5718 {
5719 int flags = FWRITE;
5720 ioctl (p->outfd, TIOCFLUSH, &flags);
5721 }
5722 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5723
5724 /* Running filters might relocate buffers or strings.
5725 Arrange to relocate BUF. */
5726 if (BUFFERP (object))
5727 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5728 else if (STRINGP (object))
5729 offset = buf - SDATA (object);
5730
5731 #ifdef EMACS_HAS_USECS
5732 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5733 #else
5734 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5735 #endif
5736
5737 if (BUFFERP (object))
5738 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5739 else if (STRINGP (object))
5740 buf = offset + SDATA (object);
5741
5742 rv = 0;
5743 }
5744 else
5745 /* This is a real error. */
5746 report_file_error ("writing to process", Fcons (proc, Qnil));
5747 }
5748 buf += rv;
5749 len -= rv;
5750 this -= rv;
5751 }
5752 }
5753 }
5754 else
5755 {
5756 signal (SIGPIPE, old_sigpipe);
5757 proc = process_sent_to;
5758 p = XPROCESS (proc);
5759 p->raw_status_new = 0;
5760 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5761 p->tick = ++process_tick;
5762 deactivate_process (proc);
5763 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5764 }
5765
5766 UNGCPRO;
5767 }
5768
5769 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5770 3, 3, 0,
5771 doc: /* Send current contents of region as input to PROCESS.
5772 PROCESS may be a process, a buffer, the name of a process or buffer, or
5773 nil, indicating the current buffer's process.
5774 Called from program, takes three arguments, PROCESS, START and END.
5775 If the region is more than 500 characters long,
5776 it is sent in several bunches. This may happen even for shorter regions.
5777 Output from processes can arrive in between bunches. */)
5778 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5779 {
5780 Lisp_Object proc;
5781 EMACS_INT start1, end1;
5782
5783 proc = get_process (process);
5784 validate_region (&start, &end);
5785
5786 if (XINT (start) < GPT && XINT (end) > GPT)
5787 move_gap (XINT (start));
5788
5789 start1 = CHAR_TO_BYTE (XINT (start));
5790 end1 = CHAR_TO_BYTE (XINT (end));
5791 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5792 Fcurrent_buffer ());
5793
5794 return Qnil;
5795 }
5796
5797 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5798 2, 2, 0,
5799 doc: /* Send PROCESS the contents of STRING as input.
5800 PROCESS may be a process, a buffer, the name of a process or buffer, or
5801 nil, indicating the current buffer's process.
5802 If STRING is more than 500 characters long,
5803 it is sent in several bunches. This may happen even for shorter strings.
5804 Output from processes can arrive in between bunches. */)
5805 (Lisp_Object process, Lisp_Object string)
5806 {
5807 Lisp_Object proc;
5808 CHECK_STRING (string);
5809 proc = get_process (process);
5810 send_process (proc, SDATA (string),
5811 SBYTES (string), string);
5812 return Qnil;
5813 }
5814 \f
5815 /* Return the foreground process group for the tty/pty that
5816 the process P uses. */
5817 static int
5818 emacs_get_tty_pgrp (struct Lisp_Process *p)
5819 {
5820 int gid = -1;
5821
5822 #ifdef TIOCGPGRP
5823 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5824 {
5825 int fd;
5826 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5827 master side. Try the slave side. */
5828 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5829
5830 if (fd != -1)
5831 {
5832 ioctl (fd, TIOCGPGRP, &gid);
5833 emacs_close (fd);
5834 }
5835 }
5836 #endif /* defined (TIOCGPGRP ) */
5837
5838 return gid;
5839 }
5840
5841 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5842 Sprocess_running_child_p, 0, 1, 0,
5843 doc: /* Return t if PROCESS has given the terminal to a child.
5844 If the operating system does not make it possible to find out,
5845 return t unconditionally. */)
5846 (Lisp_Object process)
5847 {
5848 /* Initialize in case ioctl doesn't exist or gives an error,
5849 in a way that will cause returning t. */
5850 int gid;
5851 Lisp_Object proc;
5852 struct Lisp_Process *p;
5853
5854 proc = get_process (process);
5855 p = XPROCESS (proc);
5856
5857 if (!EQ (p->type, Qreal))
5858 error ("Process %s is not a subprocess",
5859 SDATA (p->name));
5860 if (p->infd < 0)
5861 error ("Process %s is not active",
5862 SDATA (p->name));
5863
5864 gid = emacs_get_tty_pgrp (p);
5865
5866 if (gid == p->pid)
5867 return Qnil;
5868 return Qt;
5869 }
5870 \f
5871 /* send a signal number SIGNO to PROCESS.
5872 If CURRENT_GROUP is t, that means send to the process group
5873 that currently owns the terminal being used to communicate with PROCESS.
5874 This is used for various commands in shell mode.
5875 If CURRENT_GROUP is lambda, that means send to the process group
5876 that currently owns the terminal, but only if it is NOT the shell itself.
5877
5878 If NOMSG is zero, insert signal-announcements into process's buffers
5879 right away.
5880
5881 If we can, we try to signal PROCESS by sending control characters
5882 down the pty. This allows us to signal inferiors who have changed
5883 their uid, for which killpg would return an EPERM error. */
5884
5885 static void
5886 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5887 int nomsg)
5888 {
5889 Lisp_Object proc;
5890 register struct Lisp_Process *p;
5891 int gid;
5892 int no_pgrp = 0;
5893
5894 proc = get_process (process);
5895 p = XPROCESS (proc);
5896
5897 if (!EQ (p->type, Qreal))
5898 error ("Process %s is not a subprocess",
5899 SDATA (p->name));
5900 if (p->infd < 0)
5901 error ("Process %s is not active",
5902 SDATA (p->name));
5903
5904 if (!p->pty_flag)
5905 current_group = Qnil;
5906
5907 /* If we are using pgrps, get a pgrp number and make it negative. */
5908 if (NILP (current_group))
5909 /* Send the signal to the shell's process group. */
5910 gid = p->pid;
5911 else
5912 {
5913 #ifdef SIGNALS_VIA_CHARACTERS
5914 /* If possible, send signals to the entire pgrp
5915 by sending an input character to it. */
5916
5917 struct termios t;
5918 cc_t *sig_char = NULL;
5919
5920 tcgetattr (p->infd, &t);
5921
5922 switch (signo)
5923 {
5924 case SIGINT:
5925 sig_char = &t.c_cc[VINTR];
5926 break;
5927
5928 case SIGQUIT:
5929 sig_char = &t.c_cc[VQUIT];
5930 break;
5931
5932 case SIGTSTP:
5933 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5934 sig_char = &t.c_cc[VSWTCH];
5935 #else
5936 sig_char = &t.c_cc[VSUSP];
5937 #endif
5938 break;
5939 }
5940
5941 if (sig_char && *sig_char != CDISABLE)
5942 {
5943 send_process (proc, sig_char, 1, Qnil);
5944 return;
5945 }
5946 /* If we can't send the signal with a character,
5947 fall through and send it another way. */
5948
5949 /* The code above may fall through if it can't
5950 handle the signal. */
5951 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5952
5953 #ifdef TIOCGPGRP
5954 /* Get the current pgrp using the tty itself, if we have that.
5955 Otherwise, use the pty to get the pgrp.
5956 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5957 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5958 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5959 His patch indicates that if TIOCGPGRP returns an error, then
5960 we should just assume that p->pid is also the process group id. */
5961
5962 gid = emacs_get_tty_pgrp (p);
5963
5964 if (gid == -1)
5965 /* If we can't get the information, assume
5966 the shell owns the tty. */
5967 gid = p->pid;
5968
5969 /* It is not clear whether anything really can set GID to -1.
5970 Perhaps on some system one of those ioctls can or could do so.
5971 Or perhaps this is vestigial. */
5972 if (gid == -1)
5973 no_pgrp = 1;
5974 #else /* ! defined (TIOCGPGRP ) */
5975 /* Can't select pgrps on this system, so we know that
5976 the child itself heads the pgrp. */
5977 gid = p->pid;
5978 #endif /* ! defined (TIOCGPGRP ) */
5979
5980 /* If current_group is lambda, and the shell owns the terminal,
5981 don't send any signal. */
5982 if (EQ (current_group, Qlambda) && gid == p->pid)
5983 return;
5984 }
5985
5986 switch (signo)
5987 {
5988 #ifdef SIGCONT
5989 case SIGCONT:
5990 p->raw_status_new = 0;
5991 p->status = Qrun;
5992 p->tick = ++process_tick;
5993 if (!nomsg)
5994 {
5995 status_notify (NULL);
5996 redisplay_preserve_echo_area (13);
5997 }
5998 break;
5999 #endif /* ! defined (SIGCONT) */
6000 case SIGINT:
6001 case SIGQUIT:
6002 case SIGKILL:
6003 flush_pending_output (p->infd);
6004 break;
6005 }
6006
6007 /* If we don't have process groups, send the signal to the immediate
6008 subprocess. That isn't really right, but it's better than any
6009 obvious alternative. */
6010 if (no_pgrp)
6011 {
6012 kill (p->pid, signo);
6013 return;
6014 }
6015
6016 /* gid may be a pid, or minus a pgrp's number */
6017 #ifdef TIOCSIGSEND
6018 if (!NILP (current_group))
6019 {
6020 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6021 EMACS_KILLPG (gid, signo);
6022 }
6023 else
6024 {
6025 gid = - p->pid;
6026 kill (gid, signo);
6027 }
6028 #else /* ! defined (TIOCSIGSEND) */
6029 EMACS_KILLPG (gid, signo);
6030 #endif /* ! defined (TIOCSIGSEND) */
6031 }
6032
6033 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6034 doc: /* Interrupt process PROCESS.
6035 PROCESS may be a process, a buffer, or the name of a process or buffer.
6036 No arg or nil means current buffer's process.
6037 Second arg CURRENT-GROUP non-nil means send signal to
6038 the current process-group of the process's controlling terminal
6039 rather than to the process's own process group.
6040 If the process is a shell, this means interrupt current subjob
6041 rather than the shell.
6042
6043 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6044 don't send the signal. */)
6045 (Lisp_Object process, Lisp_Object current_group)
6046 {
6047 process_send_signal (process, SIGINT, current_group, 0);
6048 return process;
6049 }
6050
6051 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6052 doc: /* Kill process PROCESS. May be process or name of one.
6053 See function `interrupt-process' for more details on usage. */)
6054 (Lisp_Object process, Lisp_Object current_group)
6055 {
6056 process_send_signal (process, SIGKILL, current_group, 0);
6057 return process;
6058 }
6059
6060 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6061 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6062 See function `interrupt-process' for more details on usage. */)
6063 (Lisp_Object process, Lisp_Object current_group)
6064 {
6065 process_send_signal (process, SIGQUIT, current_group, 0);
6066 return process;
6067 }
6068
6069 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6070 doc: /* Stop process PROCESS. May be process or name of one.
6071 See function `interrupt-process' for more details on usage.
6072 If PROCESS is a network or serial process, inhibit handling of incoming
6073 traffic. */)
6074 (Lisp_Object process, Lisp_Object current_group)
6075 {
6076 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6077 {
6078 struct Lisp_Process *p;
6079
6080 p = XPROCESS (process);
6081 if (NILP (p->command)
6082 && p->infd >= 0)
6083 {
6084 FD_CLR (p->infd, &input_wait_mask);
6085 FD_CLR (p->infd, &non_keyboard_wait_mask);
6086 }
6087 p->command = Qt;
6088 return process;
6089 }
6090 #ifndef SIGTSTP
6091 error ("No SIGTSTP support");
6092 #else
6093 process_send_signal (process, SIGTSTP, current_group, 0);
6094 #endif
6095 return process;
6096 }
6097
6098 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6099 doc: /* Continue process PROCESS. May be process or name of one.
6100 See function `interrupt-process' for more details on usage.
6101 If PROCESS is a network or serial process, resume handling of incoming
6102 traffic. */)
6103 (Lisp_Object process, Lisp_Object current_group)
6104 {
6105 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6106 {
6107 struct Lisp_Process *p;
6108
6109 p = XPROCESS (process);
6110 if (EQ (p->command, Qt)
6111 && p->infd >= 0
6112 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6113 {
6114 FD_SET (p->infd, &input_wait_mask);
6115 FD_SET (p->infd, &non_keyboard_wait_mask);
6116 #ifdef WINDOWSNT
6117 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6118 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6119 #else /* not WINDOWSNT */
6120 tcflush (p->infd, TCIFLUSH);
6121 #endif /* not WINDOWSNT */
6122 }
6123 p->command = Qnil;
6124 return process;
6125 }
6126 #ifdef SIGCONT
6127 process_send_signal (process, SIGCONT, current_group, 0);
6128 #else
6129 error ("No SIGCONT support");
6130 #endif
6131 return process;
6132 }
6133
6134 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6135 2, 2, "sProcess (name or number): \nnSignal code: ",
6136 doc: /* Send PROCESS the signal with code SIGCODE.
6137 PROCESS may also be a number specifying the process id of the
6138 process to signal; in this case, the process need not be a child of
6139 this Emacs.
6140 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6141 (Lisp_Object process, Lisp_Object sigcode)
6142 {
6143 pid_t pid;
6144
6145 if (INTEGERP (process))
6146 {
6147 pid = XINT (process);
6148 goto got_it;
6149 }
6150
6151 if (FLOATP (process))
6152 {
6153 pid = (pid_t) XFLOAT_DATA (process);
6154 goto got_it;
6155 }
6156
6157 if (STRINGP (process))
6158 {
6159 Lisp_Object tem;
6160 if (tem = Fget_process (process), NILP (tem))
6161 {
6162 pid = XINT (Fstring_to_number (process, make_number (10)));
6163 if (pid > 0)
6164 goto got_it;
6165 }
6166 process = tem;
6167 }
6168 else
6169 process = get_process (process);
6170
6171 if (NILP (process))
6172 return process;
6173
6174 CHECK_PROCESS (process);
6175 pid = XPROCESS (process)->pid;
6176 if (pid <= 0)
6177 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6178
6179 got_it:
6180
6181 #define parse_signal(NAME, VALUE) \
6182 else if (!xstrcasecmp (name, NAME)) \
6183 XSETINT (sigcode, VALUE)
6184
6185 if (INTEGERP (sigcode))
6186 ;
6187 else
6188 {
6189 unsigned char *name;
6190
6191 CHECK_SYMBOL (sigcode);
6192 name = SDATA (SYMBOL_NAME (sigcode));
6193
6194 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6195 name += 3;
6196
6197 if (0)
6198 ;
6199 #ifdef SIGUSR1
6200 parse_signal ("usr1", SIGUSR1);
6201 #endif
6202 #ifdef SIGUSR2
6203 parse_signal ("usr2", SIGUSR2);
6204 #endif
6205 #ifdef SIGTERM
6206 parse_signal ("term", SIGTERM);
6207 #endif
6208 #ifdef SIGHUP
6209 parse_signal ("hup", SIGHUP);
6210 #endif
6211 #ifdef SIGINT
6212 parse_signal ("int", SIGINT);
6213 #endif
6214 #ifdef SIGQUIT
6215 parse_signal ("quit", SIGQUIT);
6216 #endif
6217 #ifdef SIGILL
6218 parse_signal ("ill", SIGILL);
6219 #endif
6220 #ifdef SIGABRT
6221 parse_signal ("abrt", SIGABRT);
6222 #endif
6223 #ifdef SIGEMT
6224 parse_signal ("emt", SIGEMT);
6225 #endif
6226 #ifdef SIGKILL
6227 parse_signal ("kill", SIGKILL);
6228 #endif
6229 #ifdef SIGFPE
6230 parse_signal ("fpe", SIGFPE);
6231 #endif
6232 #ifdef SIGBUS
6233 parse_signal ("bus", SIGBUS);
6234 #endif
6235 #ifdef SIGSEGV
6236 parse_signal ("segv", SIGSEGV);
6237 #endif
6238 #ifdef SIGSYS
6239 parse_signal ("sys", SIGSYS);
6240 #endif
6241 #ifdef SIGPIPE
6242 parse_signal ("pipe", SIGPIPE);
6243 #endif
6244 #ifdef SIGALRM
6245 parse_signal ("alrm", SIGALRM);
6246 #endif
6247 #ifdef SIGURG
6248 parse_signal ("urg", SIGURG);
6249 #endif
6250 #ifdef SIGSTOP
6251 parse_signal ("stop", SIGSTOP);
6252 #endif
6253 #ifdef SIGTSTP
6254 parse_signal ("tstp", SIGTSTP);
6255 #endif
6256 #ifdef SIGCONT
6257 parse_signal ("cont", SIGCONT);
6258 #endif
6259 #ifdef SIGCHLD
6260 parse_signal ("chld", SIGCHLD);
6261 #endif
6262 #ifdef SIGTTIN
6263 parse_signal ("ttin", SIGTTIN);
6264 #endif
6265 #ifdef SIGTTOU
6266 parse_signal ("ttou", SIGTTOU);
6267 #endif
6268 #ifdef SIGIO
6269 parse_signal ("io", SIGIO);
6270 #endif
6271 #ifdef SIGXCPU
6272 parse_signal ("xcpu", SIGXCPU);
6273 #endif
6274 #ifdef SIGXFSZ
6275 parse_signal ("xfsz", SIGXFSZ);
6276 #endif
6277 #ifdef SIGVTALRM
6278 parse_signal ("vtalrm", SIGVTALRM);
6279 #endif
6280 #ifdef SIGPROF
6281 parse_signal ("prof", SIGPROF);
6282 #endif
6283 #ifdef SIGWINCH
6284 parse_signal ("winch", SIGWINCH);
6285 #endif
6286 #ifdef SIGINFO
6287 parse_signal ("info", SIGINFO);
6288 #endif
6289 else
6290 error ("Undefined signal name %s", name);
6291 }
6292
6293 #undef parse_signal
6294
6295 return make_number (kill (pid, XINT (sigcode)));
6296 }
6297
6298 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6299 doc: /* Make PROCESS see end-of-file in its input.
6300 EOF comes after any text already sent to it.
6301 PROCESS may be a process, a buffer, the name of a process or buffer, or
6302 nil, indicating the current buffer's process.
6303 If PROCESS is a network connection, or is a process communicating
6304 through a pipe (as opposed to a pty), then you cannot send any more
6305 text to PROCESS after you call this function.
6306 If PROCESS is a serial process, wait until all output written to the
6307 process has been transmitted to the serial port. */)
6308 (Lisp_Object process)
6309 {
6310 Lisp_Object proc;
6311 struct coding_system *coding;
6312
6313 if (DATAGRAM_CONN_P (process))
6314 return process;
6315
6316 proc = get_process (process);
6317 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6318
6319 /* Make sure the process is really alive. */
6320 if (XPROCESS (proc)->raw_status_new)
6321 update_status (XPROCESS (proc));
6322 if (! EQ (XPROCESS (proc)->status, Qrun))
6323 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6324
6325 if (CODING_REQUIRE_FLUSHING (coding))
6326 {
6327 coding->mode |= CODING_MODE_LAST_BLOCK;
6328 send_process (proc, "", 0, Qnil);
6329 }
6330
6331 if (XPROCESS (proc)->pty_flag)
6332 send_process (proc, "\004", 1, Qnil);
6333 else if (EQ (XPROCESS (proc)->type, Qserial))
6334 {
6335 #ifndef WINDOWSNT
6336 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6337 error ("tcdrain() failed: %s", emacs_strerror (errno));
6338 #endif /* not WINDOWSNT */
6339 /* Do nothing on Windows because writes are blocking. */
6340 }
6341 else
6342 {
6343 int old_outfd, new_outfd;
6344
6345 #ifdef HAVE_SHUTDOWN
6346 /* If this is a network connection, or socketpair is used
6347 for communication with the subprocess, call shutdown to cause EOF.
6348 (In some old system, shutdown to socketpair doesn't work.
6349 Then we just can't win.) */
6350 if (EQ (XPROCESS (proc)->type, Qnetwork)
6351 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6352 shutdown (XPROCESS (proc)->outfd, 1);
6353 /* In case of socketpair, outfd == infd, so don't close it. */
6354 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6355 emacs_close (XPROCESS (proc)->outfd);
6356 #else /* not HAVE_SHUTDOWN */
6357 emacs_close (XPROCESS (proc)->outfd);
6358 #endif /* not HAVE_SHUTDOWN */
6359 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6360 if (new_outfd < 0)
6361 abort ();
6362 old_outfd = XPROCESS (proc)->outfd;
6363
6364 if (!proc_encode_coding_system[new_outfd])
6365 proc_encode_coding_system[new_outfd]
6366 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6367 memcpy (proc_encode_coding_system[new_outfd],
6368 proc_encode_coding_system[old_outfd],
6369 sizeof (struct coding_system));
6370 memset (proc_encode_coding_system[old_outfd], 0,
6371 sizeof (struct coding_system));
6372
6373 XPROCESS (proc)->outfd = new_outfd;
6374 }
6375 return process;
6376 }
6377 \f
6378 /* On receipt of a signal that a child status has changed, loop asking
6379 about children with changed statuses until the system says there
6380 are no more.
6381
6382 All we do is change the status; we do not run sentinels or print
6383 notifications. That is saved for the next time keyboard input is
6384 done, in order to avoid timing errors.
6385
6386 ** WARNING: this can be called during garbage collection.
6387 Therefore, it must not be fooled by the presence of mark bits in
6388 Lisp objects.
6389
6390 ** USG WARNING: Although it is not obvious from the documentation
6391 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6392 signal() before executing at least one wait(), otherwise the
6393 handler will be called again, resulting in an infinite loop. The
6394 relevant portion of the documentation reads "SIGCLD signals will be
6395 queued and the signal-catching function will be continually
6396 reentered until the queue is empty". Invoking signal() causes the
6397 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6398 Inc.
6399
6400 ** Malloc WARNING: This should never call malloc either directly or
6401 indirectly; if it does, that is a bug */
6402
6403 #ifdef SIGCHLD
6404 SIGTYPE
6405 sigchld_handler (int signo)
6406 {
6407 int old_errno = errno;
6408 Lisp_Object proc;
6409 struct Lisp_Process *p;
6410
6411 SIGNAL_THREAD_CHECK (signo);
6412
6413 while (1)
6414 {
6415 pid_t pid;
6416 int w;
6417 Lisp_Object tail;
6418
6419 #ifdef WNOHANG
6420 #ifndef WUNTRACED
6421 #define WUNTRACED 0
6422 #endif /* no WUNTRACED */
6423 /* Keep trying to get a status until we get a definitive result. */
6424 do
6425 {
6426 errno = 0;
6427 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6428 }
6429 while (pid < 0 && errno == EINTR);
6430
6431 if (pid <= 0)
6432 {
6433 /* PID == 0 means no processes found, PID == -1 means a real
6434 failure. We have done all our job, so return. */
6435
6436 errno = old_errno;
6437 return;
6438 }
6439 #else
6440 pid = wait (&w);
6441 #endif /* no WNOHANG */
6442
6443 /* Find the process that signaled us, and record its status. */
6444
6445 /* The process can have been deleted by Fdelete_process. */
6446 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6447 {
6448 Lisp_Object xpid = XCAR (tail);
6449 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6450 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6451 {
6452 XSETCAR (tail, Qnil);
6453 goto sigchld_end_of_loop;
6454 }
6455 }
6456
6457 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6458 p = 0;
6459 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6460 {
6461 proc = XCDR (XCAR (tail));
6462 p = XPROCESS (proc);
6463 if (EQ (p->type, Qreal) && p->pid == pid)
6464 break;
6465 p = 0;
6466 }
6467
6468 /* Look for an asynchronous process whose pid hasn't been filled
6469 in yet. */
6470 if (p == 0)
6471 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6472 {
6473 proc = XCDR (XCAR (tail));
6474 p = XPROCESS (proc);
6475 if (p->pid == -1)
6476 break;
6477 p = 0;
6478 }
6479
6480 /* Change the status of the process that was found. */
6481 if (p != 0)
6482 {
6483 int clear_desc_flag = 0;
6484
6485 p->tick = ++process_tick;
6486 p->raw_status = w;
6487 p->raw_status_new = 1;
6488
6489 /* If process has terminated, stop waiting for its output. */
6490 if ((WIFSIGNALED (w) || WIFEXITED (w))
6491 && p->infd >= 0)
6492 clear_desc_flag = 1;
6493
6494 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6495 if (clear_desc_flag)
6496 {
6497 FD_CLR (p->infd, &input_wait_mask);
6498 FD_CLR (p->infd, &non_keyboard_wait_mask);
6499 }
6500
6501 /* Tell wait_reading_process_output that it needs to wake up and
6502 look around. */
6503 if (input_available_clear_time)
6504 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6505 }
6506
6507 /* There was no asynchronous process found for that pid: we have
6508 a synchronous process. */
6509 else
6510 {
6511 synch_process_alive = 0;
6512
6513 /* Report the status of the synchronous process. */
6514 if (WIFEXITED (w))
6515 synch_process_retcode = WRETCODE (w);
6516 else if (WIFSIGNALED (w))
6517 synch_process_termsig = WTERMSIG (w);
6518
6519 /* Tell wait_reading_process_output that it needs to wake up and
6520 look around. */
6521 if (input_available_clear_time)
6522 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6523 }
6524
6525 sigchld_end_of_loop:
6526 ;
6527
6528 /* On some systems, we must return right away.
6529 If any more processes want to signal us, we will
6530 get another signal.
6531 Otherwise (on systems that have WNOHANG), loop around
6532 to use up all the processes that have something to tell us. */
6533 #if (defined WINDOWSNT \
6534 || (defined USG && !defined GNU_LINUX \
6535 && !(defined HPUX && defined WNOHANG)))
6536 errno = old_errno;
6537 return;
6538 #endif /* USG, but not HPUX with WNOHANG */
6539 }
6540 }
6541 #endif /* SIGCHLD */
6542 \f
6543
6544 static Lisp_Object
6545 exec_sentinel_unwind (Lisp_Object data)
6546 {
6547 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6548 return Qnil;
6549 }
6550
6551 static Lisp_Object
6552 exec_sentinel_error_handler (Lisp_Object error)
6553 {
6554 cmd_error_internal (error, "error in process sentinel: ");
6555 Vinhibit_quit = Qt;
6556 update_echo_area ();
6557 Fsleep_for (make_number (2), Qnil);
6558 return Qt;
6559 }
6560
6561 static void
6562 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6563 {
6564 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6565 register struct Lisp_Process *p = XPROCESS (proc);
6566 int count = SPECPDL_INDEX ();
6567 int outer_running_asynch_code = running_asynch_code;
6568 int waiting = waiting_for_user_input_p;
6569
6570 if (inhibit_sentinels)
6571 return;
6572
6573 /* No need to gcpro these, because all we do with them later
6574 is test them for EQness, and none of them should be a string. */
6575 odeactivate = Vdeactivate_mark;
6576 XSETBUFFER (obuffer, current_buffer);
6577 okeymap = current_buffer->keymap;
6578
6579 /* There's no good reason to let sentinels change the current
6580 buffer, and many callers of accept-process-output, sit-for, and
6581 friends don't expect current-buffer to be changed from under them. */
6582 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6583
6584 sentinel = p->sentinel;
6585 if (NILP (sentinel))
6586 return;
6587
6588 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6589 assure that it gets restored no matter how the sentinel exits. */
6590 p->sentinel = Qnil;
6591 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6592 /* Inhibit quit so that random quits don't screw up a running filter. */
6593 specbind (Qinhibit_quit, Qt);
6594 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6595
6596 /* In case we get recursively called,
6597 and we already saved the match data nonrecursively,
6598 save the same match data in safely recursive fashion. */
6599 if (outer_running_asynch_code)
6600 {
6601 Lisp_Object tem;
6602 tem = Fmatch_data (Qnil, Qnil, Qnil);
6603 restore_search_regs ();
6604 record_unwind_save_match_data ();
6605 Fset_match_data (tem, Qt);
6606 }
6607
6608 /* For speed, if a search happens within this code,
6609 save the match data in a special nonrecursive fashion. */
6610 running_asynch_code = 1;
6611
6612 internal_condition_case_1 (read_process_output_call,
6613 Fcons (sentinel,
6614 Fcons (proc, Fcons (reason, Qnil))),
6615 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6616 exec_sentinel_error_handler);
6617
6618 /* If we saved the match data nonrecursively, restore it now. */
6619 restore_search_regs ();
6620 running_asynch_code = outer_running_asynch_code;
6621
6622 Vdeactivate_mark = odeactivate;
6623
6624 /* Restore waiting_for_user_input_p as it was
6625 when we were called, in case the filter clobbered it. */
6626 waiting_for_user_input_p = waiting;
6627
6628 #if 0
6629 if (! EQ (Fcurrent_buffer (), obuffer)
6630 || ! EQ (current_buffer->keymap, okeymap))
6631 #endif
6632 /* But do it only if the caller is actually going to read events.
6633 Otherwise there's no need to make him wake up, and it could
6634 cause trouble (for example it would make sit_for return). */
6635 if (waiting_for_user_input_p == -1)
6636 record_asynch_buffer_change ();
6637
6638 unbind_to (count, Qnil);
6639 }
6640
6641 /* Report all recent events of a change in process status
6642 (either run the sentinel or output a message).
6643 This is usually done while Emacs is waiting for keyboard input
6644 but can be done at other times. */
6645
6646 static void
6647 status_notify (struct Lisp_Process *deleting_process)
6648 {
6649 register Lisp_Object proc, buffer;
6650 Lisp_Object tail, msg;
6651 struct gcpro gcpro1, gcpro2;
6652
6653 tail = Qnil;
6654 msg = Qnil;
6655 /* We need to gcpro tail; if read_process_output calls a filter
6656 which deletes a process and removes the cons to which tail points
6657 from Vprocess_alist, and then causes a GC, tail is an unprotected
6658 reference. */
6659 GCPRO2 (tail, msg);
6660
6661 /* Set this now, so that if new processes are created by sentinels
6662 that we run, we get called again to handle their status changes. */
6663 update_tick = process_tick;
6664
6665 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6666 {
6667 Lisp_Object symbol;
6668 register struct Lisp_Process *p;
6669
6670 proc = Fcdr (XCAR (tail));
6671 p = XPROCESS (proc);
6672
6673 if (p->tick != p->update_tick)
6674 {
6675 p->update_tick = p->tick;
6676
6677 /* If process is still active, read any output that remains. */
6678 while (! EQ (p->filter, Qt)
6679 && ! EQ (p->status, Qconnect)
6680 && ! EQ (p->status, Qlisten)
6681 /* Network or serial process not stopped: */
6682 && ! EQ (p->command, Qt)
6683 && p->infd >= 0
6684 && p != deleting_process
6685 && read_process_output (proc, p->infd) > 0);
6686
6687 buffer = p->buffer;
6688
6689 /* Get the text to use for the message. */
6690 if (p->raw_status_new)
6691 update_status (p);
6692 msg = status_message (p);
6693
6694 /* If process is terminated, deactivate it or delete it. */
6695 symbol = p->status;
6696 if (CONSP (p->status))
6697 symbol = XCAR (p->status);
6698
6699 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6700 || EQ (symbol, Qclosed))
6701 {
6702 if (delete_exited_processes)
6703 remove_process (proc);
6704 else
6705 deactivate_process (proc);
6706 }
6707
6708 /* The actions above may have further incremented p->tick.
6709 So set p->update_tick again
6710 so that an error in the sentinel will not cause
6711 this code to be run again. */
6712 p->update_tick = p->tick;
6713 /* Now output the message suitably. */
6714 if (!NILP (p->sentinel))
6715 exec_sentinel (proc, msg);
6716 /* Don't bother with a message in the buffer
6717 when a process becomes runnable. */
6718 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6719 {
6720 Lisp_Object tem;
6721 struct buffer *old = current_buffer;
6722 EMACS_INT opoint, opoint_byte;
6723 EMACS_INT before, before_byte;
6724
6725 /* Avoid error if buffer is deleted
6726 (probably that's why the process is dead, too) */
6727 if (NILP (XBUFFER (buffer)->name))
6728 continue;
6729 Fset_buffer (buffer);
6730
6731 opoint = PT;
6732 opoint_byte = PT_BYTE;
6733 /* Insert new output into buffer
6734 at the current end-of-output marker,
6735 thus preserving logical ordering of input and output. */
6736 if (XMARKER (p->mark)->buffer)
6737 Fgoto_char (p->mark);
6738 else
6739 SET_PT_BOTH (ZV, ZV_BYTE);
6740
6741 before = PT;
6742 before_byte = PT_BYTE;
6743
6744 tem = current_buffer->read_only;
6745 current_buffer->read_only = Qnil;
6746 insert_string ("\nProcess ");
6747 Finsert (1, &p->name);
6748 insert_string (" ");
6749 Finsert (1, &msg);
6750 current_buffer->read_only = tem;
6751 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6752
6753 if (opoint >= before)
6754 SET_PT_BOTH (opoint + (PT - before),
6755 opoint_byte + (PT_BYTE - before_byte));
6756 else
6757 SET_PT_BOTH (opoint, opoint_byte);
6758
6759 set_buffer_internal (old);
6760 }
6761 }
6762 } /* end for */
6763
6764 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6765 UNGCPRO;
6766 }
6767
6768 \f
6769 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6770 Sset_process_coding_system, 1, 3, 0,
6771 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6772 DECODING will be used to decode subprocess output and ENCODING to
6773 encode subprocess input. */)
6774 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6775 {
6776 register struct Lisp_Process *p;
6777
6778 CHECK_PROCESS (process);
6779 p = XPROCESS (process);
6780 if (p->infd < 0)
6781 error ("Input file descriptor of %s closed", SDATA (p->name));
6782 if (p->outfd < 0)
6783 error ("Output file descriptor of %s closed", SDATA (p->name));
6784 Fcheck_coding_system (decoding);
6785 Fcheck_coding_system (encoding);
6786 encoding = coding_inherit_eol_type (encoding, Qnil);
6787 p->decode_coding_system = decoding;
6788 p->encode_coding_system = encoding;
6789 setup_process_coding_systems (process);
6790
6791 return Qnil;
6792 }
6793
6794 DEFUN ("process-coding-system",
6795 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6796 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6797 (register Lisp_Object process)
6798 {
6799 CHECK_PROCESS (process);
6800 return Fcons (XPROCESS (process)->decode_coding_system,
6801 XPROCESS (process)->encode_coding_system);
6802 }
6803
6804 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6805 Sset_process_filter_multibyte, 2, 2, 0,
6806 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6807 If FLAG is non-nil, the filter is given multibyte strings.
6808 If FLAG is nil, the filter is given unibyte strings. In this case,
6809 all character code conversion except for end-of-line conversion is
6810 suppressed. */)
6811 (Lisp_Object process, Lisp_Object flag)
6812 {
6813 register struct Lisp_Process *p;
6814
6815 CHECK_PROCESS (process);
6816 p = XPROCESS (process);
6817 if (NILP (flag))
6818 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6819 setup_process_coding_systems (process);
6820
6821 return Qnil;
6822 }
6823
6824 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6825 Sprocess_filter_multibyte_p, 1, 1, 0,
6826 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6827 (Lisp_Object process)
6828 {
6829 register struct Lisp_Process *p;
6830 struct coding_system *coding;
6831
6832 CHECK_PROCESS (process);
6833 p = XPROCESS (process);
6834 coding = proc_decode_coding_system[p->infd];
6835 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6836 }
6837
6838
6839 \f
6840
6841 void
6842 add_gpm_wait_descriptor (int desc)
6843 {
6844 add_keyboard_wait_descriptor (desc);
6845 }
6846
6847 void
6848 delete_gpm_wait_descriptor (int desc)
6849 {
6850 delete_keyboard_wait_descriptor (desc);
6851 }
6852
6853 /* Return nonzero if *MASK has a bit set
6854 that corresponds to one of the keyboard input descriptors. */
6855
6856 static int
6857 keyboard_bit_set (fd_set *mask)
6858 {
6859 int fd;
6860
6861 for (fd = 0; fd <= max_input_desc; fd++)
6862 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6863 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6864 return 1;
6865
6866 return 0;
6867 }
6868
6869 #else /* not subprocesses */
6870
6871 /* Defined on msdos.c. */
6872 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6873 EMACS_TIME *);
6874
6875 /* Implementation of wait_reading_process_output, assuming that there
6876 are no subprocesses. Used only by the MS-DOS build.
6877
6878 Wait for timeout to elapse and/or keyboard input to be available.
6879
6880 time_limit is:
6881 timeout in seconds, or
6882 zero for no limit, or
6883 -1 means gobble data immediately available but don't wait for any.
6884
6885 read_kbd is a Lisp_Object:
6886 0 to ignore keyboard input, or
6887 1 to return when input is available, or
6888 -1 means caller will actually read the input, so don't throw to
6889 the quit handler.
6890
6891 see full version for other parameters. We know that wait_proc will
6892 always be NULL, since `subprocesses' isn't defined.
6893
6894 do_display != 0 means redisplay should be done to show subprocess
6895 output that arrives.
6896
6897 Return true if we received input from any process. */
6898
6899 int
6900 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6901 int do_display,
6902 Lisp_Object wait_for_cell,
6903 struct Lisp_Process *wait_proc, int just_wait_proc)
6904 {
6905 register int nfds;
6906 EMACS_TIME end_time, timeout;
6907 SELECT_TYPE waitchannels;
6908 int xerrno;
6909
6910 /* What does time_limit really mean? */
6911 if (time_limit || microsecs)
6912 {
6913 EMACS_GET_TIME (end_time);
6914 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6915 EMACS_ADD_TIME (end_time, end_time, timeout);
6916 }
6917
6918 /* Turn off periodic alarms (in case they are in use)
6919 and then turn off any other atimers,
6920 because the select emulator uses alarms. */
6921 stop_polling ();
6922 turn_on_atimers (0);
6923
6924 while (1)
6925 {
6926 int timeout_reduced_for_timers = 0;
6927
6928 /* If calling from keyboard input, do not quit
6929 since we want to return C-g as an input character.
6930 Otherwise, do pending quit if requested. */
6931 if (read_kbd >= 0)
6932 QUIT;
6933
6934 /* Exit now if the cell we're waiting for became non-nil. */
6935 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6936 break;
6937
6938 /* Compute time from now till when time limit is up */
6939 /* Exit if already run out */
6940 if (time_limit == -1)
6941 {
6942 /* -1 specified for timeout means
6943 gobble output available now
6944 but don't wait at all. */
6945
6946 EMACS_SET_SECS_USECS (timeout, 0, 0);
6947 }
6948 else if (time_limit || microsecs)
6949 {
6950 EMACS_GET_TIME (timeout);
6951 EMACS_SUB_TIME (timeout, end_time, timeout);
6952 if (EMACS_TIME_NEG_P (timeout))
6953 break;
6954 }
6955 else
6956 {
6957 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6958 }
6959
6960 /* If our caller will not immediately handle keyboard events,
6961 run timer events directly.
6962 (Callers that will immediately read keyboard events
6963 call timer_delay on their own.) */
6964 if (NILP (wait_for_cell))
6965 {
6966 EMACS_TIME timer_delay;
6967
6968 do
6969 {
6970 int old_timers_run = timers_run;
6971 timer_delay = timer_check (1);
6972 if (timers_run != old_timers_run && do_display)
6973 /* We must retry, since a timer may have requeued itself
6974 and that could alter the time delay. */
6975 redisplay_preserve_echo_area (14);
6976 else
6977 break;
6978 }
6979 while (!detect_input_pending ());
6980
6981 /* If there is unread keyboard input, also return. */
6982 if (read_kbd != 0
6983 && requeued_events_pending_p ())
6984 break;
6985
6986 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6987 {
6988 EMACS_TIME difference;
6989 EMACS_SUB_TIME (difference, timer_delay, timeout);
6990 if (EMACS_TIME_NEG_P (difference))
6991 {
6992 timeout = timer_delay;
6993 timeout_reduced_for_timers = 1;
6994 }
6995 }
6996 }
6997
6998 /* Cause C-g and alarm signals to take immediate action,
6999 and cause input available signals to zero out timeout. */
7000 if (read_kbd < 0)
7001 set_waiting_for_input (&timeout);
7002
7003 /* Wait till there is something to do. */
7004
7005 if (! read_kbd && NILP (wait_for_cell))
7006 FD_ZERO (&waitchannels);
7007 else
7008 FD_SET (0, &waitchannels);
7009
7010 /* If a frame has been newly mapped and needs updating,
7011 reprocess its display stuff. */
7012 if (frame_garbaged && do_display)
7013 {
7014 clear_waiting_for_input ();
7015 redisplay_preserve_echo_area (15);
7016 if (read_kbd < 0)
7017 set_waiting_for_input (&timeout);
7018 }
7019
7020 if (read_kbd && detect_input_pending ())
7021 {
7022 nfds = 0;
7023 FD_ZERO (&waitchannels);
7024 }
7025 else
7026 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7027 &timeout);
7028
7029 xerrno = errno;
7030
7031 /* Make C-g and alarm signals set flags again */
7032 clear_waiting_for_input ();
7033
7034 /* If we woke up due to SIGWINCH, actually change size now. */
7035 do_pending_window_change (0);
7036
7037 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7038 /* We waited the full specified time, so return now. */
7039 break;
7040
7041 if (nfds == -1)
7042 {
7043 /* If the system call was interrupted, then go around the
7044 loop again. */
7045 if (xerrno == EINTR)
7046 FD_ZERO (&waitchannels);
7047 else
7048 error ("select error: %s", emacs_strerror (xerrno));
7049 }
7050
7051 /* Check for keyboard input */
7052
7053 if (read_kbd
7054 && detect_input_pending_run_timers (do_display))
7055 {
7056 swallow_events (do_display);
7057 if (detect_input_pending_run_timers (do_display))
7058 break;
7059 }
7060
7061 /* If there is unread keyboard input, also return. */
7062 if (read_kbd
7063 && requeued_events_pending_p ())
7064 break;
7065
7066 /* If wait_for_cell. check for keyboard input
7067 but don't run any timers.
7068 ??? (It seems wrong to me to check for keyboard
7069 input at all when wait_for_cell, but the code
7070 has been this way since July 1994.
7071 Try changing this after version 19.31.) */
7072 if (! NILP (wait_for_cell)
7073 && detect_input_pending ())
7074 {
7075 swallow_events (do_display);
7076 if (detect_input_pending ())
7077 break;
7078 }
7079
7080 /* Exit now if the cell we're waiting for became non-nil. */
7081 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7082 break;
7083 }
7084
7085 start_polling ();
7086
7087 return 0;
7088 }
7089
7090 #endif /* not subprocesses */
7091
7092 /* The following functions are needed even if async subprocesses are
7093 not supported. Some of them are no-op stubs in that case. */
7094
7095 /* Add DESC to the set of keyboard input descriptors. */
7096
7097 void
7098 add_keyboard_wait_descriptor (int desc)
7099 {
7100 #ifdef subprocesses /* actually means "not MSDOS" */
7101 FD_SET (desc, &input_wait_mask);
7102 FD_SET (desc, &non_process_wait_mask);
7103 if (desc > max_input_desc)
7104 max_input_desc = desc;
7105 #endif
7106 }
7107
7108 /* From now on, do not expect DESC to give keyboard input. */
7109
7110 void
7111 delete_keyboard_wait_descriptor (int desc)
7112 {
7113 #ifdef subprocesses
7114 int fd;
7115 int lim = max_input_desc;
7116
7117 FD_CLR (desc, &input_wait_mask);
7118 FD_CLR (desc, &non_process_wait_mask);
7119
7120 if (desc == max_input_desc)
7121 for (fd = 0; fd < lim; fd++)
7122 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
7123 max_input_desc = fd;
7124 #endif
7125 }
7126
7127 /* Setup coding systems of PROCESS. */
7128
7129 void
7130 setup_process_coding_systems (Lisp_Object process)
7131 {
7132 #ifdef subprocesses
7133 struct Lisp_Process *p = XPROCESS (process);
7134 int inch = p->infd;
7135 int outch = p->outfd;
7136 Lisp_Object coding_system;
7137
7138 if (inch < 0 || outch < 0)
7139 return;
7140
7141 if (!proc_decode_coding_system[inch])
7142 proc_decode_coding_system[inch]
7143 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7144 coding_system = p->decode_coding_system;
7145 if (! NILP (p->filter))
7146 ;
7147 else if (BUFFERP (p->buffer))
7148 {
7149 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7150 coding_system = raw_text_coding_system (coding_system);
7151 }
7152 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7153
7154 if (!proc_encode_coding_system[outch])
7155 proc_encode_coding_system[outch]
7156 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7157 setup_coding_system (p->encode_coding_system,
7158 proc_encode_coding_system[outch]);
7159 #endif
7160 }
7161
7162 /* Close all descriptors currently in use for communication
7163 with subprocess. This is used in a newly-forked subprocess
7164 to get rid of irrelevant descriptors. */
7165
7166 void
7167 close_process_descs (void)
7168 {
7169 #ifndef DOS_NT
7170 int i;
7171 for (i = 0; i < MAXDESC; i++)
7172 {
7173 Lisp_Object process;
7174 process = chan_process[i];
7175 if (!NILP (process))
7176 {
7177 int in = XPROCESS (process)->infd;
7178 int out = XPROCESS (process)->outfd;
7179 if (in >= 0)
7180 emacs_close (in);
7181 if (out >= 0 && in != out)
7182 emacs_close (out);
7183 }
7184 }
7185 #endif
7186 }
7187
7188 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7189 doc: /* Return the (or a) process associated with BUFFER.
7190 BUFFER may be a buffer or the name of one. */)
7191 (register Lisp_Object buffer)
7192 {
7193 #ifdef subprocesses
7194 register Lisp_Object buf, tail, proc;
7195
7196 if (NILP (buffer)) return Qnil;
7197 buf = Fget_buffer (buffer);
7198 if (NILP (buf)) return Qnil;
7199
7200 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7201 {
7202 proc = Fcdr (XCAR (tail));
7203 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7204 return proc;
7205 }
7206 #endif /* subprocesses */
7207 return Qnil;
7208 }
7209
7210 DEFUN ("process-inherit-coding-system-flag",
7211 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7212 1, 1, 0,
7213 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7214 If this flag is t, `buffer-file-coding-system' of the buffer
7215 associated with PROCESS will inherit the coding system used to decode
7216 the process output. */)
7217 (register Lisp_Object process)
7218 {
7219 #ifdef subprocesses
7220 CHECK_PROCESS (process);
7221 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7222 #else
7223 /* Ignore the argument and return the value of
7224 inherit-process-coding-system. */
7225 return inherit_process_coding_system ? Qt : Qnil;
7226 #endif
7227 }
7228
7229 /* Kill all processes associated with `buffer'.
7230 If `buffer' is nil, kill all processes */
7231
7232 void
7233 kill_buffer_processes (Lisp_Object buffer)
7234 {
7235 #ifdef subprocesses
7236 Lisp_Object tail, proc;
7237
7238 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7239 {
7240 proc = XCDR (XCAR (tail));
7241 if (PROCESSP (proc)
7242 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7243 {
7244 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7245 Fdelete_process (proc);
7246 else if (XPROCESS (proc)->infd >= 0)
7247 process_send_signal (proc, SIGHUP, Qnil, 1);
7248 }
7249 }
7250 #else /* subprocesses */
7251 /* Since we have no subprocesses, this does nothing. */
7252 #endif /* subprocesses */
7253 }
7254
7255 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7256 0, 0, 0,
7257 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7258 This is intended for use by asynchronous process output filters and sentinels. */)
7259 (void)
7260 {
7261 #ifdef subprocesses
7262 return (waiting_for_user_input_p ? Qt : Qnil);
7263 #else
7264 return Qnil;
7265 #endif
7266 }
7267
7268 /* Stop reading input from keyboard sources. */
7269
7270 void
7271 hold_keyboard_input (void)
7272 {
7273 kbd_is_on_hold = 1;
7274 }
7275
7276 /* Resume reading input from keyboard sources. */
7277
7278 void
7279 unhold_keyboard_input (void)
7280 {
7281 kbd_is_on_hold = 0;
7282 }
7283
7284 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7285
7286 int
7287 kbd_on_hold_p (void)
7288 {
7289 return kbd_is_on_hold;
7290 }
7291
7292 \f
7293 /* Enumeration of and access to system processes a-la ps(1). */
7294
7295 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7296 0, 0, 0,
7297 doc: /* Return a list of numerical process IDs of all running processes.
7298 If this functionality is unsupported, return nil.
7299
7300 See `process-attributes' for getting attributes of a process given its ID. */)
7301 (void)
7302 {
7303 return list_system_processes ();
7304 }
7305
7306 DEFUN ("process-attributes", Fprocess_attributes,
7307 Sprocess_attributes, 1, 1, 0,
7308 doc: /* Return attributes of the process given by its PID, a number.
7309
7310 Value is an alist where each element is a cons cell of the form
7311
7312 \(KEY . VALUE)
7313
7314 If this functionality is unsupported, the value is nil.
7315
7316 See `list-system-processes' for getting a list of all process IDs.
7317
7318 The KEYs of the attributes that this function may return are listed
7319 below, together with the type of the associated VALUE (in parentheses).
7320 Not all platforms support all of these attributes; unsupported
7321 attributes will not appear in the returned alist.
7322 Unless explicitly indicated otherwise, numbers can have either
7323 integer or floating point values.
7324
7325 euid -- Effective user User ID of the process (number)
7326 user -- User name corresponding to euid (string)
7327 egid -- Effective user Group ID of the process (number)
7328 group -- Group name corresponding to egid (string)
7329 comm -- Command name (executable name only) (string)
7330 state -- Process state code, such as "S", "R", or "T" (string)
7331 ppid -- Parent process ID (number)
7332 pgrp -- Process group ID (number)
7333 sess -- Session ID, i.e. process ID of session leader (number)
7334 ttname -- Controlling tty name (string)
7335 tpgid -- ID of foreground process group on the process's tty (number)
7336 minflt -- number of minor page faults (number)
7337 majflt -- number of major page faults (number)
7338 cminflt -- cumulative number of minor page faults (number)
7339 cmajflt -- cumulative number of major page faults (number)
7340 utime -- user time used by the process, in the (HIGH LOW USEC) format
7341 stime -- system time used by the process, in the (HIGH LOW USEC) format
7342 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7343 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7344 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7345 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7346 pri -- priority of the process (number)
7347 nice -- nice value of the process (number)
7348 thcount -- process thread count (number)
7349 start -- time the process started, in the (HIGH LOW USEC) format
7350 vsize -- virtual memory size of the process in KB's (number)
7351 rss -- resident set size of the process in KB's (number)
7352 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7353 pcpu -- percents of CPU time used by the process (floating-point number)
7354 pmem -- percents of total physical memory used by process's resident set
7355 (floating-point number)
7356 args -- command line which invoked the process (string). */)
7357 ( Lisp_Object pid)
7358 {
7359 return system_process_attributes (pid);
7360 }
7361
7362 \f
7363 void
7364 init_process (void)
7365 {
7366 #ifdef subprocesses
7367 register int i;
7368
7369 inhibit_sentinels = 0;
7370
7371 #ifdef SIGCHLD
7372 #ifndef CANNOT_DUMP
7373 if (! noninteractive || initialized)
7374 #endif
7375 signal (SIGCHLD, sigchld_handler);
7376 #endif
7377
7378 FD_ZERO (&input_wait_mask);
7379 FD_ZERO (&non_keyboard_wait_mask);
7380 FD_ZERO (&non_process_wait_mask);
7381 FD_ZERO (&write_mask);
7382 max_process_desc = 0;
7383 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7384
7385 #ifdef NON_BLOCKING_CONNECT
7386 FD_ZERO (&connect_wait_mask);
7387 num_pending_connects = 0;
7388 #endif
7389
7390 #ifdef ADAPTIVE_READ_BUFFERING
7391 process_output_delay_count = 0;
7392 process_output_skip = 0;
7393 #endif
7394
7395 /* Don't do this, it caused infinite select loops. The display
7396 method should call add_keyboard_wait_descriptor on stdin if it
7397 needs that. */
7398 #if 0
7399 FD_SET (0, &input_wait_mask);
7400 #endif
7401
7402 Vprocess_alist = Qnil;
7403 #ifdef SIGCHLD
7404 deleted_pid_list = Qnil;
7405 #endif
7406 for (i = 0; i < MAXDESC; i++)
7407 {
7408 chan_process[i] = Qnil;
7409 proc_buffered_char[i] = -1;
7410 }
7411 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7412 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7413 #ifdef DATAGRAM_SOCKETS
7414 memset (datagram_address, 0, sizeof datagram_address);
7415 #endif
7416
7417 {
7418 Lisp_Object subfeatures = Qnil;
7419 const struct socket_options *sopt;
7420
7421 #define ADD_SUBFEATURE(key, val) \
7422 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7423
7424 #ifdef NON_BLOCKING_CONNECT
7425 ADD_SUBFEATURE (QCnowait, Qt);
7426 #endif
7427 #ifdef DATAGRAM_SOCKETS
7428 ADD_SUBFEATURE (QCtype, Qdatagram);
7429 #endif
7430 #ifdef HAVE_SEQPACKET
7431 ADD_SUBFEATURE (QCtype, Qseqpacket);
7432 #endif
7433 #ifdef HAVE_LOCAL_SOCKETS
7434 ADD_SUBFEATURE (QCfamily, Qlocal);
7435 #endif
7436 ADD_SUBFEATURE (QCfamily, Qipv4);
7437 #ifdef AF_INET6
7438 ADD_SUBFEATURE (QCfamily, Qipv6);
7439 #endif
7440 #ifdef HAVE_GETSOCKNAME
7441 ADD_SUBFEATURE (QCservice, Qt);
7442 #endif
7443 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7444 ADD_SUBFEATURE (QCserver, Qt);
7445 #endif
7446
7447 for (sopt = socket_options; sopt->name; sopt++)
7448 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7449
7450 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7451 }
7452
7453 #if defined (DARWIN_OS)
7454 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7455 processes. As such, we only change the default value. */
7456 if (initialized)
7457 {
7458 const char *release = get_operating_system_release ();
7459 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7460 && release[1] == '.')) {
7461 Vprocess_connection_type = Qnil;
7462 }
7463 }
7464 #endif
7465 #endif /* subprocesses */
7466 kbd_is_on_hold = 0;
7467 }
7468
7469 void
7470 syms_of_process (void)
7471 {
7472 #ifdef subprocesses
7473
7474 Qprocessp = intern_c_string ("processp");
7475 staticpro (&Qprocessp);
7476 Qrun = intern_c_string ("run");
7477 staticpro (&Qrun);
7478 Qstop = intern_c_string ("stop");
7479 staticpro (&Qstop);
7480 Qsignal = intern_c_string ("signal");
7481 staticpro (&Qsignal);
7482
7483 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7484 here again.
7485
7486 Qexit = intern_c_string ("exit");
7487 staticpro (&Qexit); */
7488
7489 Qopen = intern_c_string ("open");
7490 staticpro (&Qopen);
7491 Qclosed = intern_c_string ("closed");
7492 staticpro (&Qclosed);
7493 Qconnect = intern_c_string ("connect");
7494 staticpro (&Qconnect);
7495 Qfailed = intern_c_string ("failed");
7496 staticpro (&Qfailed);
7497 Qlisten = intern_c_string ("listen");
7498 staticpro (&Qlisten);
7499 Qlocal = intern_c_string ("local");
7500 staticpro (&Qlocal);
7501 Qipv4 = intern_c_string ("ipv4");
7502 staticpro (&Qipv4);
7503 #ifdef AF_INET6
7504 Qipv6 = intern_c_string ("ipv6");
7505 staticpro (&Qipv6);
7506 #endif
7507 Qdatagram = intern_c_string ("datagram");
7508 staticpro (&Qdatagram);
7509 Qseqpacket = intern_c_string ("seqpacket");
7510 staticpro (&Qseqpacket);
7511
7512 QCport = intern_c_string (":port");
7513 staticpro (&QCport);
7514 QCspeed = intern_c_string (":speed");
7515 staticpro (&QCspeed);
7516 QCprocess = intern_c_string (":process");
7517 staticpro (&QCprocess);
7518
7519 QCbytesize = intern_c_string (":bytesize");
7520 staticpro (&QCbytesize);
7521 QCstopbits = intern_c_string (":stopbits");
7522 staticpro (&QCstopbits);
7523 QCparity = intern_c_string (":parity");
7524 staticpro (&QCparity);
7525 Qodd = intern_c_string ("odd");
7526 staticpro (&Qodd);
7527 Qeven = intern_c_string ("even");
7528 staticpro (&Qeven);
7529 QCflowcontrol = intern_c_string (":flowcontrol");
7530 staticpro (&QCflowcontrol);
7531 Qhw = intern_c_string ("hw");
7532 staticpro (&Qhw);
7533 Qsw = intern_c_string ("sw");
7534 staticpro (&Qsw);
7535 QCsummary = intern_c_string (":summary");
7536 staticpro (&QCsummary);
7537
7538 Qreal = intern_c_string ("real");
7539 staticpro (&Qreal);
7540 Qnetwork = intern_c_string ("network");
7541 staticpro (&Qnetwork);
7542 Qserial = intern_c_string ("serial");
7543 staticpro (&Qserial);
7544 QCbuffer = intern_c_string (":buffer");
7545 staticpro (&QCbuffer);
7546 QChost = intern_c_string (":host");
7547 staticpro (&QChost);
7548 QCservice = intern_c_string (":service");
7549 staticpro (&QCservice);
7550 QClocal = intern_c_string (":local");
7551 staticpro (&QClocal);
7552 QCremote = intern_c_string (":remote");
7553 staticpro (&QCremote);
7554 QCcoding = intern_c_string (":coding");
7555 staticpro (&QCcoding);
7556 QCserver = intern_c_string (":server");
7557 staticpro (&QCserver);
7558 QCnowait = intern_c_string (":nowait");
7559 staticpro (&QCnowait);
7560 QCsentinel = intern_c_string (":sentinel");
7561 staticpro (&QCsentinel);
7562 QClog = intern_c_string (":log");
7563 staticpro (&QClog);
7564 QCnoquery = intern_c_string (":noquery");
7565 staticpro (&QCnoquery);
7566 QCstop = intern_c_string (":stop");
7567 staticpro (&QCstop);
7568 QCoptions = intern_c_string (":options");
7569 staticpro (&QCoptions);
7570 QCplist = intern_c_string (":plist");
7571 staticpro (&QCplist);
7572
7573 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7574 staticpro (&Qlast_nonmenu_event);
7575
7576 staticpro (&Vprocess_alist);
7577 #ifdef SIGCHLD
7578 staticpro (&deleted_pid_list);
7579 #endif
7580
7581 #endif /* subprocesses */
7582
7583 QCname = intern_c_string (":name");
7584 staticpro (&QCname);
7585 QCtype = intern_c_string (":type");
7586 staticpro (&QCtype);
7587
7588 Qeuid = intern_c_string ("euid");
7589 staticpro (&Qeuid);
7590 Qegid = intern_c_string ("egid");
7591 staticpro (&Qegid);
7592 Quser = intern_c_string ("user");
7593 staticpro (&Quser);
7594 Qgroup = intern_c_string ("group");
7595 staticpro (&Qgroup);
7596 Qcomm = intern_c_string ("comm");
7597 staticpro (&Qcomm);
7598 Qstate = intern_c_string ("state");
7599 staticpro (&Qstate);
7600 Qppid = intern_c_string ("ppid");
7601 staticpro (&Qppid);
7602 Qpgrp = intern_c_string ("pgrp");
7603 staticpro (&Qpgrp);
7604 Qsess = intern_c_string ("sess");
7605 staticpro (&Qsess);
7606 Qttname = intern_c_string ("ttname");
7607 staticpro (&Qttname);
7608 Qtpgid = intern_c_string ("tpgid");
7609 staticpro (&Qtpgid);
7610 Qminflt = intern_c_string ("minflt");
7611 staticpro (&Qminflt);
7612 Qmajflt = intern_c_string ("majflt");
7613 staticpro (&Qmajflt);
7614 Qcminflt = intern_c_string ("cminflt");
7615 staticpro (&Qcminflt);
7616 Qcmajflt = intern_c_string ("cmajflt");
7617 staticpro (&Qcmajflt);
7618 Qutime = intern_c_string ("utime");
7619 staticpro (&Qutime);
7620 Qstime = intern_c_string ("stime");
7621 staticpro (&Qstime);
7622 Qtime = intern_c_string ("time");
7623 staticpro (&Qtime);
7624 Qcutime = intern_c_string ("cutime");
7625 staticpro (&Qcutime);
7626 Qcstime = intern_c_string ("cstime");
7627 staticpro (&Qcstime);
7628 Qctime = intern_c_string ("ctime");
7629 staticpro (&Qctime);
7630 Qpri = intern_c_string ("pri");
7631 staticpro (&Qpri);
7632 Qnice = intern_c_string ("nice");
7633 staticpro (&Qnice);
7634 Qthcount = intern_c_string ("thcount");
7635 staticpro (&Qthcount);
7636 Qstart = intern_c_string ("start");
7637 staticpro (&Qstart);
7638 Qvsize = intern_c_string ("vsize");
7639 staticpro (&Qvsize);
7640 Qrss = intern_c_string ("rss");
7641 staticpro (&Qrss);
7642 Qetime = intern_c_string ("etime");
7643 staticpro (&Qetime);
7644 Qpcpu = intern_c_string ("pcpu");
7645 staticpro (&Qpcpu);
7646 Qpmem = intern_c_string ("pmem");
7647 staticpro (&Qpmem);
7648 Qargs = intern_c_string ("args");
7649 staticpro (&Qargs);
7650
7651 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7652 doc: /* *Non-nil means delete processes immediately when they exit.
7653 A value of nil means don't delete them until `list-processes' is run. */);
7654
7655 delete_exited_processes = 1;
7656
7657 #ifdef subprocesses
7658 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7659 doc: /* Control type of device used to communicate with subprocesses.
7660 Values are nil to use a pipe, or t or `pty' to use a pty.
7661 The value has no effect if the system has no ptys or if all ptys are busy:
7662 then a pipe is used in any case.
7663 The value takes effect when `start-process' is called. */);
7664 Vprocess_connection_type = Qt;
7665
7666 #ifdef ADAPTIVE_READ_BUFFERING
7667 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7668 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7669 On some systems, when Emacs reads the output from a subprocess, the output data
7670 is read in very small blocks, potentially resulting in very poor performance.
7671 This behavior can be remedied to some extent by setting this variable to a
7672 non-nil value, as it will automatically delay reading from such processes, to
7673 allow them to produce more output before Emacs tries to read it.
7674 If the value is t, the delay is reset after each write to the process; any other
7675 non-nil value means that the delay is not reset on write.
7676 The variable takes effect when `start-process' is called. */);
7677 Vprocess_adaptive_read_buffering = Qt;
7678 #endif
7679
7680 defsubr (&Sprocessp);
7681 defsubr (&Sget_process);
7682 defsubr (&Sdelete_process);
7683 defsubr (&Sprocess_status);
7684 defsubr (&Sprocess_exit_status);
7685 defsubr (&Sprocess_id);
7686 defsubr (&Sprocess_name);
7687 defsubr (&Sprocess_tty_name);
7688 defsubr (&Sprocess_command);
7689 defsubr (&Sset_process_buffer);
7690 defsubr (&Sprocess_buffer);
7691 defsubr (&Sprocess_mark);
7692 defsubr (&Sset_process_filter);
7693 defsubr (&Sprocess_filter);
7694 defsubr (&Sset_process_sentinel);
7695 defsubr (&Sprocess_sentinel);
7696 defsubr (&Sset_process_window_size);
7697 defsubr (&Sset_process_inherit_coding_system_flag);
7698 defsubr (&Sset_process_query_on_exit_flag);
7699 defsubr (&Sprocess_query_on_exit_flag);
7700 defsubr (&Sprocess_contact);
7701 defsubr (&Sprocess_plist);
7702 defsubr (&Sset_process_plist);
7703 defsubr (&Slist_processes);
7704 defsubr (&Sprocess_list);
7705 defsubr (&Sstart_process);
7706 defsubr (&Sserial_process_configure);
7707 defsubr (&Smake_serial_process);
7708 defsubr (&Sset_network_process_option);
7709 defsubr (&Smake_network_process);
7710 defsubr (&Sformat_network_address);
7711 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7712 #ifdef SIOCGIFCONF
7713 defsubr (&Snetwork_interface_list);
7714 #endif
7715 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7716 defsubr (&Snetwork_interface_info);
7717 #endif
7718 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
7719 #ifdef DATAGRAM_SOCKETS
7720 defsubr (&Sprocess_datagram_address);
7721 defsubr (&Sset_process_datagram_address);
7722 #endif
7723 defsubr (&Saccept_process_output);
7724 defsubr (&Sprocess_send_region);
7725 defsubr (&Sprocess_send_string);
7726 defsubr (&Sinterrupt_process);
7727 defsubr (&Skill_process);
7728 defsubr (&Squit_process);
7729 defsubr (&Sstop_process);
7730 defsubr (&Scontinue_process);
7731 defsubr (&Sprocess_running_child_p);
7732 defsubr (&Sprocess_send_eof);
7733 defsubr (&Ssignal_process);
7734 defsubr (&Swaiting_for_user_input_p);
7735 defsubr (&Sprocess_type);
7736 defsubr (&Sset_process_coding_system);
7737 defsubr (&Sprocess_coding_system);
7738 defsubr (&Sset_process_filter_multibyte);
7739 defsubr (&Sprocess_filter_multibyte_p);
7740
7741 #endif /* subprocesses */
7742
7743 defsubr (&Sget_buffer_process);
7744 defsubr (&Sprocess_inherit_coding_system_flag);
7745 defsubr (&Slist_system_processes);
7746 defsubr (&Sprocess_attributes);
7747 }
7748
7749 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7750 (do not change this comment) */